Blog>
Snippets

Implementing Conditional Logic within Dynamic Arrays Using TanStack Form

Explain how to implement conditional logic within dynamic arrays in TanStack Form, such as displaying different input fields based on previous choices or array lengths.
import { useFieldArray, useForm } from 'react-hook-form';

function MyForm() {
  const { control, register, handleSubmit, watch } = useForm();
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'items'
  });
  const onSubmit = data => console.log(data);

  // Example: Watching the value of another field to apply conditional logic
  const watchField = watch('type');

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((field, index) => (
        <div key={field.id}>
          {/* Conditional rendering based on another field's value */}
          {watchField === 'special' && index === 0 ? (
            <input
              {...register(`items[${index}].specialInput`)}
              placeholder='Special Input for first item if type is special'
            />
          ) : (
            <input
              {...register(`items[${index}].regularInput`)}
              placeholder='Regular Input'
            />
          )}
          <button type='button' onClick={() => remove(index)}>Remove</button>
        </div>
      ))}
      <button type='button' onClick={() => append({})}>Add Item</button>
      <input type='submit' />
    </form>
  );
}
This example demonstrates implementing conditional logic within a dynamic array using the TanStack Form (via the react-hook-form library). It showcases how to use the `watch` function to keep track of changes in other form fields, and based on that, conditionally render inputs within the dynamic array. In this case, if the 'type' is 'special' and it's the first item in the array, a special input field will be rendered; otherwise, a regular input field is displayed.