useFieldArray in React Hook Form
In web page interactions, forms are common elements. For form validation/management,
react-hook-form
is a commonly used and excellent helper library. For example,useFieldArray
is used for managing array values, andformContext
is used for complex nested component forms. Understanding these usage patterns helps you use it more effectively.
Use Case
When handling forms, you sometimes need to process array form items, such as when users can dynamically add N rows of form items. useFieldArray is designed for this type of array handling.
Example
function FormTest() {
const {control, register, getValues} = useForm();
const {fields, append, prepend, remove, swap, move, insert} = useFieldArray({
control, // control props comes from useForm (optional: if you are using FormProvider)
name: "test", // unique name for your Field Array
});
console.log(fields, 'fields');
return (
<form>
{fields.map((field, index) => (
<div><input
key={field.id} // important to include key with field's id
{...register(`test.${index}.value`)}
/></div>
))}
<Button onClick={() => {
append({
value: 1,
})
}}>
Add
</Button>
{
JSON.stringify(getValues())
}
</form>
);
}
As shown above, when clicking the Button to add, fields can automatically insert a new value, and each value can also be monitored and maintained through register/controller.
Important Details
The append value must be an object - for example, append(1) won’t work. This means fields must maintain objects, so test.${index}.value
cannot be set as test.${index}
.
Final Thoughts
For form handling requirements, I recommend trying this library as a solution.