Blog>
Snippets

Implementing Dynamic Forms with Conditional Fields

Illustrates the technique to dynamically add or remove input fields based on user actions or selections, employing conditional logic within TanStack Form for a more interactive form experience.
import { useState } from 'react';
import { useFieldArray, useForm } from 'react-hook-form';

function DynamicForm() {
  const { register, control, handleSubmit } = useForm();
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'items',
  });
  
  const onSubmit = data => console.log(data);
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((item, index) => (
        <div key={item.id}>
          <input {...register(`items[${index}].name`)} placeholder='Item name' />
          
          {/* Conditional field example */}
          <input {...register(`items[${index}].description`)} placeholder='Description' />
          
          <button type='button' onClick={() => remove(index)}>Remove</button>
        </div>
      ))}
      <button type='button' onClick={() => append({ name: '', description: '' })}>Add Item</button>
      <input type='submit' />
    </form>
  );
}

export default DynamicForm;
This code implements a dynamic form using React and the react-hook-form library, which includes TanStack Form (formerly react-hook-form). It allows adding and removing items with each item having a name and a conditional description field. The 'useFieldArray' hook manages the dynamic fields.