Blog>
Snippets

Implementing Conditional Form Fields

Show how to dynamically add or remove form fields based on user input or selections using TanStack Form, illustrating state management for conditional rendering.
import { useRef } from 'react';
import { useForm, useFieldArray } from '@tanstack/react-form';

function ConditionalFormFields() {
  const formRef = useRef();
  const form = useForm({
    defaultValues: {
      userType: '',
      details: [{ detail: '' }]
    }
  });

  const { fields, append, remove } = useFieldArray({
    form,
    name: 'details'
  });

  const handleUserTypeChange = (e) => {
    const userType = e.target.value;
    form.setFieldValue('userType', userType);
    if (userType === 'admin') {
      append({ detail: '' }); // Add an additional field if the user is an admin
    } else {
      while(fields.length > 1) remove(0); // Remove extra fields if not admin
    }
  };

  return (
    <form ref={formRef}>
      <select name="userType" onChange={handleUserTypeChange}>
        <option value="">Select User Type</option>
        <option value="user">User</option>
        <option value="admin">Admin</option>
      </select>
      {fields.map((field, index) => (
        <input
          key={field.id}
          {...form.register(`details.${index}.detail`)}
        />
      ))}
    </form>
  );
}
This code demonstrates how to dynamically add or remove form fields based on user selection using TanStack Form. Upon selecting a 'userType', an additional detail input field is added if the selected type is 'admin'. Conversely, any extra fields are removed if the userType is not 'admin', showcasing conditional rendering and state management with the use of hooks provided by TanStack Form.