Blog>
Snippets

Dynamically Adding Form Fields with useForm

Illustrate how to dynamically add and remove input fields in a form managed by useForm, emphasizing the use of array fields and the handling of their state.
import React from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
Import necessary hooks from react-hook-form.
function DynamicForm() {
    const { register, control, handleSubmit } = useForm({
        defaultValues: {
            users: [{ name: '', email: '' }]
        }
    });
    const { fields, append, remove } = useFieldArray({
        control,
        name: 'users'
    });
    return (
        <form onSubmit={handleSubmit(data => console.log(data))}>
            {fields.map((item, index) => (
                <div key={item.id}>
                    <input {...register(`users[${index}].name`)} placeholder='Name' />
                    <input {...register(`users[${index}].email`)} placeholder='Email' />
                    <button type='button' onClick={() => remove(index)}>Remove</button>
                </div>
            ))}
            <button type='button' onClick={() => append({ name: '', email: '' })}>Add User</button>
            <input type='submit' />
        </form>
    );
}
Defines a dynamic form component. It utilizes useForm for form handling and useFieldArray to manage an array of user fields. Users can dynamically add or remove sets of name and email fields.