Blog>
Snippets

Efficiently Handling Dynamic Form Arrays

Demonstrate using the `useFieldArray` hook in TanStack Form to dynamically add, remove, and update fields within an array.
import { useForm, useFieldArray } from '@tanstack/react-form';
First, import the necessary hooks from TanStack React Form.
const DynamicForm = () => { 
 const form = useForm({ 
 defaultValues: { 
 items: [{ name: '' }] 
 }, 
 }); 
 const { fields, append, remove } = useFieldArray({ 
 control: form.control, 
 name: 'items', 
 });
Initialize TanStack Form with useForm hook and useFieldArray to manage the dynamic array. 'items' will store our array fields.
return ( 
 <form onSubmit={form.handleSubmit(data => console.log(data))}> 
 {fields.map((field, index) => ( 
 <div key={field.id}> 
 <input 
 name={`items[${index}].name`} 
 ref={form.register()} 
 defaultValue={field.name} 
 /> 
 <button type="button" onClick={() => remove(index)}>Remove</button> 
 </div> 
 ))} 
 <button type="button" onClick={() => append({ name: '' })}>Add More</button> 
 <button type="submit">Submit</button> 
 </form> 
 ); 
};
Render the form. Utilize the map function to iterate over the fields. For each field, render an input and a 'Remove' button. Include an 'Add More' button to append new items and a 'Submit' button.