Blog>
Snippets

Adding Items to Dynamic Arrays with TanStack Form

Show how to dynamically add new items to an array field in a form managed by TanStack Form, including form validation for the new item.
import { useForm, useFieldArray } from '@tanstack/react-form';
First, import useForm and useFieldArray hooks from TanStack Form to handle the form and manage dynamic array fields.
const MyForm = () => {
  const {
    Form,
    values,
    getFieldProps
  } = useForm({
    defaultValues: { items: [] }
  });
  const { fields, append } = useFieldArray({
    name: 'items'
  });
Initialize the form with useForm hook and useFieldArray to manage the dynamic array. The 'items' field will hold our dynamic array.
const addItem = () => {
  append({ name: '', isValid: false });
};
Define a function, addItem, that uses the append method from useFieldArray to add a new item to the array. Each item has a 'name' and an 'isValid' property for demonstration.
return (
  <Form>
    {fields.map((field, index) => (
      <div key={field.id}>
        <input {...getFieldProps(`items.[${index}].name`)} placeholder='Item Name' />
        {/* Add any validation logic or additional fields here */}
      </div>
    ))}
    <button type='button' onClick={addItem}>Add Item</button>
    <button type='submit'>Submit</button>
  </Form>
);
Render the form, dynamically creating input fields for each item in the array. Include a button to add items by calling addItem.
};

export default MyForm;
Complete the component and export it. This form component is ready to handle dynamic arrays with an option to add new items.