Blog>
Snippets

Dynamic Input Creation with TanStack Form

Showcase how to dynamically add and remove input fields in a form using TanStack Form, enabling users to control the number of inputs for their data submission.
import { useForm, useFieldArray } from '@tanstack/react-form';
First, import useForm and useFieldArray from @tanstack/react-form to manage the form and dynamically manipulate the field arrays.
function DynamicInputForm() {
  const form = useForm({
    defaultValues: {
      inputs: [''] // Start with one input
    }
  });
  const { fields, append, remove } = useFieldArray({
    form,
    name: 'inputs' // The key in your form values holding the dynamic fields
  });
Create a React component that uses useForm to initialize the form with a single input. useFieldArray is then used to manage the dynamic addition and removal of input fields.
return (
  <form onSubmit={form.handleSubmit(values => console.log(values))}>
    {fields.map((field, index) => (
      <div key={field.id}>
        <input {...form.register(`inputs.${index}`)} />
        <button type='button' onClick={() => remove(index)}>Remove</button>
      </div>
    ))}
    <button type='button' onClick={() => append('')}>Add Input</button>
    <button type='submit'>Submit</button>
  </form>
);
Inside the component's return statement, map over the fields to render the input elements. Provide buttons to remove an input field or add a new one, alongside the form submission button. Use form.handleSubmit to handle form submission.
}

export default DynamicInputForm;
This code creates a dynamic form where users can add or remove input fields before submitting. The useForm hook initializes the form state and useFieldArray manages the dynamic addition and subtraction of inputs, ensuring the form adjusts its values accordingly.