Removing Items from a Dynamic Array in TanStack Form
Provide an example of how to remove specific items from a dynamic array in a form, focusing on the manipulation of the form's state to achieve this.
import { useFieldArray, useForm } from 'react-hook-form';
Import useFieldArray along with useForm from react-hook-form.
const { control } = useForm();
Instantiate useForm to use its control object, essential for managing field arrays.
const { fields, append, remove } = useFieldArray({ control, name: 'items' });
Initialize useFieldArray with control and a name to manage a dynamic array of items.
const handleRemoveItem = index => { remove(index); };
Define a function that removes an item at a specific index from the dynamic array.
{fields.map((field, index) => (
<button type='button' onClick={() => handleRemoveItem(index)}>Remove</button>
))}
Render a button next to each item that removes the item from the array when clicked.