Back

useMultistepForm

A React hook for building multistep forms with ease.

1 / 2

Signup to Continue

Your password is very strong

Hook snippet

Create a file called useMultistepForm.tsx with this snippet and import it in your component.

export function useMultistepForm(steps: ReactElement[]) {
  const [currentStepIndex, setCurrentStepIndex] = useState(0);
  
  function next() {
    setCurrentStepIndex((i) => {
      if (i >= steps.length - 1) return i;
      return ++i;
    });
  };

  function back() {
    setCurrentStepIndex((i) => {
      if (i <= 0) return i;
      return --i;
    });
  };

  function goTo(index: number) {
    setCurrentStepIndex(index);
  };

  return {
    currentStepIndex,
    step: steps[currentStepIndex],
    steps,
    isFirstStep: currentStepIndex === 0,
    isLastStep: currentStepIndex === steps.length - 1,
    goTo,
    next,
    back,
  };
};

Usage

Create an object for initialData.

const initialData = {
  fullName: "",
  email: "",
  password: "",
  confirmPassword: "",
  isOtpVerified: false,
};

Import the hook and use it in your component. You can pass an array of React elements as an argument. Don't forget to pass a key prop to each element.

const [data, setData] = useState<IFormData>(initialData);

const updateFields = (fields: Partial<IFormData>) => {
  setData((prev) => ({ ...prev, ...fields }));
};

const {
  steps,
  step,
  currentStepIndex,
  isLastStep,
  isFirstStep,
  next,
  back,
  goTo,
} = useMultistepForm([
  <EmailSignup key="email-signup" {...data} updateFields={updateFields} />,
  <EmailVerification key="email-verification" {...data} updateFields={updateFields} />,
]);

If you want to display a progress bar above the form, Use the Stepper component.

Made by Dhvanit. Visit my portfolio.