Adding New Items to a Dynamic Array in TanStack Form
Showcase the process of adding new items to a dynamic array within a form, including the use of a button to trigger the addition.
import { useFieldArray, useForm } from 'react-hook-form';
Importing necessary hooks from react-hook-form.
const { control } = useForm();
Initializing the useForm hook to control the form.
const { fields, append } = useFieldArray({ control, name: 'items' });
Initializing the useFieldArray hook to manage dynamic items array.
const addItem = () => { append({ itemName: '', quantity: 0 }); };
Defines a function to add a new item with default values.
return (
<div>
{fields.map((field, index) => (
<input key={field.id} name={`items[${index}].itemName`} />
))}
<button onClick={addItem}>Add Item</button>
</div>
);
Renders the dynamic array of inputs and a button that adds a new item when clicked.