Skip to main content

useFormFieldArray

The useFormFieldArray is custom hook for working with uncontrolled Field Arrays (dynamic inputs). This hook supplies you with functions for manipulating the array/list of fields.

Submit feedback
github
import { useFormFieldArray } from '@uhg-abyss/web/hooks/useFormFieldArray';

Usage

Fields

This object contains the defaultValue and key for all your inputs. It's important to assign defaultValue to the inputs.

  • The field.id (and not index) must be added as the component key to prevent re-renders breaking the fields.
// ✅ correct:
{fields.map((field, index) => (
<div key={field.id}>
<TextInput ... />
</div>
))}
// ✅ correct:
{fields.map((field, index) => <TextInput key={field.id} ... />)}
// ❌ incorrect:
{fields.map((field, index) => <TextInput key={index} ... />)}

const { fields } = useFieldArray({
keyName: 'key', // by default key name is id, and input value with name id will be omitted
});
{
fields.map((field, index) => (
<div key={field.key}>
// key name changed
<TextInput {...register('test.id')} /> // input value id will be retained
</div>
));
}

  • When you append, prepend, insert and update the field array, the obj can't be empty object rather need to supply all your input's defaultValues.
append();
append({});
append({ firstName: 'bill', lastName: 'luo' });

Append

Use the append() function to append input/inputs to the end of your fields and focus.

Prepend

Use the prepend() function to prepend input/inputs to the start of your fields and focus.

Insert

Use the insert() function to insert input/inputs at particular position and focus.

Swap

Use the swap() function to swap input/inputs position.

Move

Use the move() function to move input/inputs to another position.

Replace

Use the replace() function to replace the entire field array values with a custom list of objects.

Remove

Use the remove() function to remove elements at a particular position (or positions) in the list, or remove all of them when no index is provided.

Additional documentation

Abyss's useFormFieldArray hook is simply an alias of React Hook Form's useFieldArray hook. You can view the official documentation to learn more.

Table of Contents