LogRocket Blog

Building a reusable multi-step form with React Hook Form and Zod

thumbnail

Building a Reusable Multi-Step Form with React Hook Form and Zod

In this guide, we will be building a reusable multi-step form component in React using React Hook Form and Zod for validation. We will be using the following packages:

  • Vite: The build tool for our React.js application
  • React Hook Form: A library for managing forms in React
  • Zod: A schema validation library with static type inference
  • shadcn: A collection of reusable React components
  • Motion: For adding animations

Setting Up the Project

  1. Create a new React app with Vite and TypeScript:
npm init @vitejs/app my-multi-step-form --template react-ts
  1. Install the required packages:
npm install react-hook-form zod @shadcn/react motion

Component Structure

We will define a schema for each step in the form, which includes the title, order, validation schema, component to render, icon, and field keys. This allows us to have a unified type for all fields in the multi-step form, making it less error-prone.

Component Implementation

The main component will manage the form state and navigation using React Context. It will track the current form step, form progress, navigation functions, and the list of form step objects. It will also handle form submission and validation using React Hook Form.

  1. Form Context: The context provides form methods to all child components. It includes state and navigation functions to interact with the form's state.

  2. Form Initialization: The form is initialized using React Hook Form, with validation against the schema. Input fields related to the current step are validated before submission.

  3. Navigation Functions: Functions like nextStep, prevStep, and jumpToStep allow users to navigate between form steps.

  4. Field Validation: Before moving to the next step, input fields related to the current step are validated using React Hook Form.

By following this structure, we create a reusable multi-step form component in React that is easy to manage, configure, and interact with.