Blog>
Snippets

Dynamically Adding Fields to a Form

Show how to dynamically add input fields to a form managed by TanStack Form based on user action, such as clicking a button.
import { useForm, useFieldArray } from '@tanstack/react-form';
Imports the necessary hooks from TanStack Form.
const MyForm = () => {
  const { form, handleSubmit } = useForm({
    defaultValues: { emails: [{ address: '' }] }
  });
  const { fields, append } = useFieldArray({
    control: form.control,
    name: 'emails'
  });
Sets up the form with TanStack Form, using useForm to manage the form state and useFieldArray for dynamic array fields.
return (
  <form onSubmit={handleSubmit(data => console.log(data))}>
    {fields.map((field, index) => (
      <div key={field.id}>
        <input
          {...form.register(`emails.${index}.address`)}
          defaultValue={field.address}
        />
      </div>
    ))}
    <button type="button" onClick={() => append({ address: '' })}>Add More</button>
    <button type="submit">Submit</button>
  </form>
);
Renders the form with dynamic input fields. Uses the 'append' method to add a new email address field.
};

export default MyForm;
Exports the form component.