useFieldArray

Creates a reactive field array store of a specific field array within a form store.

const fieldArray = useFieldArray<TSchema, TFieldArrayPath>(form, config);

Generics

Parameters

Explanation

With useFieldArray you create a reactive field array store for a specific array field within your form. The field array store provides reactive access to the array items (by their IDs), validation errors, touched state, and more. This is particularly useful when working with dynamic arrays of fields that users can add or remove. Use the item IDs as the key when mapping over the array items.

Returns

Examples

The following example shows how useFieldArray can be used.

Todo list

import {
  Field,
  insert,
  remove,
  useFieldArray,
  useForm,
} from '@formisch/react-native';
import { Button, Text, TextInput, View } from 'react-native';
import * as v from 'valibot';

const TodoSchema = v.object({
  todos: v.array(
    v.object({
      label: v.pipe(v.string(), v.nonEmpty()),
    })
  ),
});

export default function TodosScreen() {
  const todoForm = useForm({ schema: TodoSchema });
  const fieldArray = useFieldArray(todoForm, { path: ['todos'] });

  return (
    <View>
      {fieldArray.items.map((item, index) => (
        <View key={item}>
          <Field of={todoForm} path={['todos', index, 'label']}>
            {(field) => (
              <View>
                <TextInput {...field.props} value={field.input} />
                {field.errors && <Text>{field.errors[0]}</Text>}
              </View>
            )}
          </Field>
          <Button
            title="Remove"
            onPress={() => remove(todoForm, { path: ['todos'], at: index })}
          />
        </View>
      ))}
      {fieldArray.errors && <Text>{fieldArray.errors[0]}</Text>}
      <Button
        title="Add todo"
        onPress={() =>
          insert(todoForm, { path: ['todos'], initialInput: { label: '' } })
        }
      />
    </View>
  );
}

The following APIs can be combined with useFieldArray.

Hooks

Components

Methods

Contributors

Thanks to all the contributors who helped make this page better!

  • GitHub profile picture of @fabian-hiller

Partners

Thanks to our partners who support the project ideally and financially.

Sponsors

Thanks to our GitHub sponsors who support the project financially.

  • GitHub profile picture of @vasilii-kovalev
  • GitHub profile picture of @UpwayShop
  • GitHub profile picture of @ruiaraujo012
  • GitHub profile picture of @hyunbinseo
  • GitHub profile picture of @nickytonline
  • GitHub profile picture of @kibertoad
  • GitHub profile picture of @caegdeveloper
  • GitHub profile picture of @Thanaen
  • GitHub profile picture of @bmoyroud
  • GitHub profile picture of @ysknsid25
  • GitHub profile picture of @dslatkin