Handling Dynamic Form Fields with useFieldArray in TanStack Form
Provide an example of using useFieldArray hook from TanStack Form for managing dynamic form fields, such as dynamically adding or removing input fields for a multi-input form.
import { useForm, useFieldArray } from '@tanstack/react-hook-form';
First, import useForm and useFieldArray hooks from @tanstack/react-hook-form.
function DynamicForm() {
const { register, control, handleSubmit } = useForm();
const { fields, append, remove } = useFieldArray({
control,
name: 'testFields'
});
Inside your component, initialize useForm and useFieldArray. 'fields' will hold your dynamic fields, 'append' is used to add fields, and 'remove' is for removing fields.
const onSubmit = data => console.log(data);
Define the onSubmit function that logs form data to the console.
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((field, index) => (
<div key={field.id}>
<input {...register(`testFields.${index}.value`)} />
<button type="button" onClick={() => remove(index)}>Remove</button>
</div>
))}
<button type="button" onClick={() => append({ value: '' })}>Add Field</button>
<input type="submit" />
</form>
);
Render the form. Dynamically generate input fields based on 'fields'. Include remove and append actions.
} // Don't forget to close your component function.
Closing the component function.