Blog>
Snippets

Setup and Initialize TanStack Form with Dynamic Arrays

Demonstrate how to initialize TanStack Form in a React component and set up a dynamic array field for handling multiple user inputs.
import React from 'react';
import { useFieldArray, useForm } from 'react-hook-form';
Import necessary hooks from react-hook-form for managing forms and dynamic arrays.
function DynamicForm() {
  const { register, control, handleSubmit, formState: { errors } } = useForm();
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'users'
  });
Initialize the useForm hook for form control and useFieldArray for managing a dynamic array of users.
const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((field, index) => (
        <div key={field.id}>
          <input {...register(`users[${index}].name`)} />
          <button type='button' onClick={() => remove(index)}>Delete</button>
        </div>
      ))}
      <button type='button' onClick={() => append({ name: '' })}>Add User</button>
      <input type='submit' />
    </form>
  );
}

export default DynamicForm;
Defines the form structure. Dynamically generates input fields for each item in the 'users' array. Provides buttons to add a new user field or remove an existing one. Submits the form data to the onSubmit function.