Blog>
Snippets

Dynamic Form Fields Based on User Input

Illustrate how to dynamically add or remove form fields in response to user input using TanStack Form, ensuring each dynamically added field remains accessible.
import { useForm, useFieldArray } from 'tanstack-form-react';
First, import useForm for creating the form instance, and useFieldArray for managing dynamic fields.
function DynamicForm() {
  const form = useForm({
    defaultValues: { dynamicFields: [{}] }
  });
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: 'dynamicFields'
  });
In the component, create the form instance with useForm. Initialize the dynamic fields with useFieldArray hook, specifying the control from the form instance and the name of the field array.
return (
  <form onSubmit={form.handleSubmit(data => console.log(data))}>
    {fields.map((field, index) => (
      <div key={field.id}>
        <input {...form.register(`dynamicFields.${index}.value`)} />
        <button type='button' onClick={() => remove(index)}>Remove</button>
      </div>
    ))}
    <button type='button' onClick={() => append({})}>Add Field</button>
    <button type='submit'>Submit</button>
  </form>
);
Render the form. For each field in the dynamicFields array, render an input field. Provide a button to remove the current field by calling remove(index), and a button to append a new field to the dynamicFields array.
}
export default DynamicForm;
Close the DynamicForm component and export it for use in your application.