Blog>
Snippets

Creating a Multi-Step Form with Navigation

Demonstrate creating a multi-step form using TanStack Form, focusing on handling state transitions between steps and using context to pass state.
import { useForm, useStep } from 'react-hook-form';

function MultiStepForm() {
  const { nextStep, prevStep, step } = useStep({
    steps: ['personalDetails', 'contactInfo', 'confirmation'],
    initialStep: 0,
  });
  const methods = useForm();

  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  };

  return (
    <form onSubmit={methods.handleSubmit(onSubmit)}>
      {step === 'personalDetails' && <PersonalDetailsForm />}
      {step === 'contactInfo' && <ContactInfoForm />}
      {step === 'confirmation' && <ConfirmationStep />}
      <button type='button' onClick={prevStep}>Back</button>
      <button type='button' onClick={nextStep}>Next</button>
      {step === 'confirmation' && <button type='submit'>Submit</button>}
    </form>
  );
}
This piece of code declares a multi-step form using TanStack's useForm and useStep hooks. It includes navigation between steps and a submit handler that alerts the form data.
function PersonalDetailsForm() {
  const { register } = useFormContext(); 

  return (
    <div>
      <label htmlFor='firstName'>First Name</label>
      <input id='firstName' {...register('firstName')} />
      <label htmlFor='lastName'>Last Name</label>
      <input id='lastName' {...register('lastName')} />
    </div>
  );
}
Defines the 'PersonalDetailsForm' component with first name and last name fields managed by useFormContext for sharing form state.
function ContactInfoForm() {
  const { register } = useFormContext();

  return (
    <div>
      <label htmlFor='email'>Email Address</label>
      <input id='email' type='email' {...register('email')} />
      <label htmlFor='phone'>Phone Number</label>
      <input id='phone' type='tel' {...register('phone')} />
    </div>
  );
}
Creates a 'ContactInfoForm' component for collecting email and phone number, utilizing useFormContext from TanStack Form for state management.
function ConfirmationStep() {
  return (
    <div>
      <h3>Confirmation Step</h3>
      <p>Please review your information and click 'Submit' to finish.</p>
    </div>
  );
}
This last piece outlines a simple 'ConfirmationStep' component for the final review before form submission.