Blog>
Snippets

Dynamic Form Fields with TanStack

Illustrate how to dynamically add or remove form fields in a TanStack form based on user input or external data triggers.
import { useFieldArray, useForm } from '@tanstack/react-form';
Import useForm and useFieldArray from TanStack for form and dynamic field management.
function DynamicFormFields() {
  const form = useForm({
    defaultValues: {
      users: [{ name: '' }], // Starting with one empty user
    },
  });

  const users = useFieldArray({
    form,
    name: 'users',
  });

  return (
    // Form JSX with dynamic fields
  );
}
Define a component with a form that has a dynamic field array named 'users'. We initialize it with an empty object to indicate one user field.
users.fields.map((field, index) => (
  <div key={field.id}>
    <input {...form.register(`users.${index}.name`)} />
    <button type='button' onClick={() => users.remove(index)}>Remove</button>
  </div>
))
Iterate over each 'user' field and render an input for the 'name' attribute. Include a 'Remove' button for each field to remove the respective field from the array.
<button type='button' onClick={() => users.append({ name: '' })}>Add User</button>
Provide an 'Add User' button outside the loop to append a new user object to the fields, allowing dynamic addition of fields.
<form onSubmit={form.handleSubmit((data) => console.log(data))}>
  { /* Dynamic users field rendered here */ }
  <button type='submit'>Submit</button>
</form>
Wrap the dynamic fields and 'Add User' button in a form element, using handleSubmit from useForm to handle form submission.