Blog>
Snippets

Managing Dynamic Form Arrays

Provide an example of how to manage dynamic form arrays with TanStack Form, allowing users to add, remove, and edit entries of a list of items within a form.
import { useForm, useFieldArray } from 'tanstack form-react';
Initial import of useForm hook for form state management, and useFieldArray hook for dynamic form array manipulation.
function MyForm() {
  const { register, control, handleSubmit } = useForm();
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'items'
  });

  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((item, index) => (
        <div key={item.id}>
          <input {...register(`items.[${index}].name`)} />
          <button type='button' onClick={() => remove(index)}>Remove</button>
        </div>
      ))}
      <button type='button' onClick={() => append({ name: '' })}>Add Item</button>
      <input type='submit' />
    </form>
  );
}
Defining a form component using useForm for basic form controls and useFieldArray to manage a dynamic array of items. The form includes functionality to add, remove, and edit items.