ReactJS

Building Multi-Step Forms in React

Ayushi Bhadauria
Ayushi BhadauriaSep 20, 2024
Building Multi-Step Forms in React

Introduction:

Managing complex forms can be a daunting task, especially when the form requires multiple steps to complete. React's single-form approach often leads to cumbersome code and poor user experience. Multi-step forms break down the process into manageable chunks, enhancing usability and keeping users engaged. They simplify validation, improve organization, and offer a more structured approach to collecting extensive data. By implementing multi-step forms, developers can create a more intuitive and efficient user experience, making complex data entry tasks feel less overwhelming and more organized.

Prerequisites:

  • Node.js and npm
  • React
  • Typescript
  • React hook form

Navigating Complex Forms: The Case for Multi-Step Forms in React

Why Multi-Step Forms Matter

Building forms with React can quickly become a challenge, especially when dealing with complex, multi-step processes. Traditional form handling can be tedious, involving verbose setup for state management, validation, and submission. This complexity grows with each step you add, making it easy to feel overwhelmed by the task.

The Need for Multi-Step Forms

Multi-step forms address this by breaking down complex input processes into manageable stages. This approach improves user experience by guiding users through the form in a structured manner, reducing cognitive load, and enhancing form completion rates. However, implementing multi-step forms requires careful planning and effective state management to ensure a seamless flow.

Simplifying Multi-Step Forms with React

Leveraging React's component-based architecture and state management capabilities, you can create efficient multi-step forms that are both user-friendly and maintainable. In this blog post, we will explore strategies for building multi-step forms in React, focusing on state handling, dynamic rendering, and user navigation. By the end, you'll have a clear understanding of how to implement multi-step forms effectively, improving both user experience and development efficiency.

Blog Image

Navigating the Multi-Step Form Setup in React

Creating a seamless user experience often requires breaking down lengthy forms into manageable segments. In this guide, we will explore the implementation of a multi-step form using React and TypeScript. By leveraging React Hook Form, we’ll simplify form state management and validation across multiple steps. This approach not only enhances user experience by guiding users through the form incrementally but also maintains clarity and efficiency in data handling. We’ll walk through the setup and organization of each step, demonstrating how to create a fluid and intuitive form submission process.

Initializing React Application : To create a React application, you need to start by creating a project folder in your root directory.

1//Create react app using the following command
2npx create-react-app multistep-form --template typescript
3
4//Install the required library
5npm i react-hook-form
6npm install @mui/material
7npm install @emotion/react @emotion/styled

Setting Up Project

  1. Project Structure : Within your project directory, locate your App.tsx file which acts as the main entry point for your React application.
  2. Creating Components :
    • Create a Components Folder : Inside your project, create a folder named components to organize your reusable components.
    • Create MultiStepController.tsx : This component will handle the overall management of form steps and state transitions, encapsulating the logic required for navigating between steps and processing form data.
    • Add Files for Multi-Step Form
      • MultistepForm.tsx : This file will contain the React component responsible for rendering the multi-step form. It manages the form state, handles step transitions, and integrates with the MultiStepController for managing the multi-step logic.
      • ReusableTextField.tsx : This component provides a reusable text field with integrated validation using React Hook Form. It simplifies form field management across different steps.

This structure will ensure your code remains modular and maintainable, facilitating easier management and extension of your multi-step form features.

1// App.tsx
2
3import MultiStepFormController from "./components/MultiStepFormController";
4
5const App = () = > {
6  return (<div style = {{width : "100%"}}><MultiStepFormController /></ div>);
7};
8
9export default App;

In the App component, we are rendering the MultiStepController component, which is a key part of our application’s interface for managing multi-step form functionality.

1//MultiStepFormController.tsx
2
3export interface IFormData {
4  firstName?: string;
5  lastName?: string;
6  age?: number | null;
7  email?: string;
8  contactNo?: number | null;
9  city?: string;
10  country?: string;
11  zipCode?: number | null;
12}
13
14const initialFormData: IFormData = {
15  firstName: "",
16  lastName: "",
17  age: 0,
18  email: "",
19  contactNo: 0,
20  city: "",
21  country: "",
22  zipCode: 0,
23};
24
25const MultiStepFormController = () => {
26  const [formData, setFormData] = useState<IFormData>(initialFormData);
27  const [step, setStep] = useState<number>(1);
28
29  let currentContent: JSX.Element | undefined;
30
31  switch (step) {
32    case 1:
33      currentContent = (
34        <MultiStepForm
35          currentStep={step}
36          setStep={setStep}
37          setFormData={setFormData}
38          formData={{
39            firstName: initialFormData.firstName,
40            lastName: initialFormData.lastName,
41            age: initialFormData.age,
42          }}
43        />
44      );
45      break;
46    case 2:
47      currentContent = (
48        <MultiStepForm
49          currentStep={step}
50          setStep={setStep}
51          setFormData={setFormData}
52          formData={{
53            email: initialFormData.email,
54            contactNo: initialFormData.contactNo,
55          }}
56        />
57      );
58      break;
59    case 3:
60      currentContent = (
61        <MultiStepForm
62          currentStep={step}
63          setStep={setStep}
64          setFormData={setFormData}
65          formData={{
66            city: initialFormData.city,
67            country: initialFormData.country,
68            zipCode: initialFormData.zipCode,
69          }}
70        />
71      );
72      break;
73    default:
74      currentContent = (
75        <Box>
76          <Box>
77            <Typography>
78              Your details have been submitted successfully!
79            </Typography>
80
81            <Grid container spacing={2}>
82              //Rendering Submitted Form Data
83            </Grid>
84          </Box>
85        </Box>
86      );
87  }
88
89  return <>{currentContent}</>;
90};
91
92export default MultiStepFormController;

The MultiStepFormController component manages the multi-step form process by controlling the current step and form data. Here’s a brief overview of its key functions:

  • State Management
    • formData : Holds the current values of the form fields, initialized with default values in initialFormData.
    • step : Tracks the current step of the multi-step form, starting at step 1.
  • Content Rendering
    • currentContent : A variable that holds the JSX element to be rendered based on the current step. It uses a switch statement to determine which MultiStepForm component to display.
  • Form Submission
    • In the default case of the switch statement, after all steps are completed, the form data is displayed in a summary format. This summary shows all the collected data from the previous steps.
  • Return Statement
    • The component returns currentContent, which will be the form for the current step or the summary view, based on the step state.

Overall, the MultiStepFormController component orchestrates the multi-step form process, handling the transitions between steps and managing form data.

1//MultistepForm.tsx
2
3interface IMultistepForm {
4  formData: IFormData;
5  setFormData: React.Dispatch<React.SetStateAction<IFormData>>;
6  currentStep: number;
7  setStep: React.Dispatch<React.SetStateAction<number>>;
8}
9
10const steps = [
11  "Personal Information",
12  "Contact Information",
13  "Location Details",
14];
15
16const MultistepForm: React.FC<IMultistepForm> = ({
17  formData,
18  setFormData,
19  currentStep,
20  setStep,
21}) => {
22  const {
23    handleSubmit,
24    control,
25    formState: { errors },
26    getValues,
27  } = useForm<IFormData>({
28    defaultValues: formData,
29  });
30
31  const handleNextStep = (data: IFormData) => {
32    setFormData((prevData) => ({ ...prevData, ...data }));
33    setStep((step) => step + 1);
34  };
35
36  const handleBackStep = () => {
37    setStep((step) => step - 1);
38  };
39
40  const onSubmit = (data: IFormData) => {
41    setStep((step) => step + 1);
42    setFormData((prevData) => ({ ...prevData, ...data }));
43    console.log("Final Data Submitted:", getValues());
44  };
45
46  return (
47    <Box>
48      <Box>
49        <Stepper activeStep={currentStep - 1}>
50          {steps.map((label, index) => (
51            <Step key={index}>
52              <StepLabel>
53                <Typography>{label}</Typography>
54              </StepLabel>
55            </Step>
56          ))}
57        </Stepper>
58        <form
59          onSubmit={handleSubmit(currentStep === 3 ? onSubmit : handleNextStep)}
60        >
61          {currentStep === 1 && (
62            <>
63              <ReusableTextField
64                name="firstName"
65                control={control}
66                label="First Name"
67                rules={{ required: "First name is required" }}
68              />
69              <ReusableTextField
70                name="lastName"
71                control={control}
72                label="Last Name"
73              />
74              <ReusableTextField
75                name="age"
76                control={control}
77                label="Age"
78                type="number"
79              />
80            </>
81          )}
82          {currentStep === 2 && (
83            <>
84              <ReusableTextField
85                name="email"
86                control={control}
87                label="Email"
88                rules={{ required: "Email is required" }}
89              />
90              <ReusableTextField
91                name="contactNo"
92                control={control}
93                label="Contact No"
94                type="number"
95              />
96            </>
97          )}
98          {currentStep === 3 && (
99            <>
100              <ReusableTextField name="city" control={control} label="City" />
101              <ReusableTextField
102                name="country"
103                control={control}
104                label="Country"
105              />
106              <ReusableTextField
107                name="zipCode"
108                control={control}
109                label="Zip Code"
110                type="number"
111              />
112            </>
113          )}
114          <Box>
115            {currentStep > 1 && <Button>Back</Button>}
116            <Button variant="contained" type="submit">
117              {currentStep === 3 ? "Submit" : "Next"}
118            </Button>
119          </Box>
120        </form>
121      </Box>
122    </Box>
123  );
124};
125
126export default MultistepForm;

The MultiStepForm component handles the step-by-step navigation of the form process. 

Step Handling

  • currentStep controls which section of the form is displayed.
  • The form has three steps:
    • Step 1 : Personal Information (First Name, Last Name, Age)
    • Step 2 : Contact Information (Email, Contact No)
    • Step 3 : Location Details (City, Country, Zip Code)

Step Transitions

  • handleNextStep : Updates the form data and proceeds to the next step.
  • handleBackStepb : Allows users to navigate back to the previous step.

Form Completion

  • On Step 3, the “Next” button changes to “Submit.”
  • Once submitted, the final data is captured and processed.

This setup efficiently manages step navigation, ensuring a smooth flow through the form.

1//ReusableTextField.tsx
2
3interface ControlledTextFieldProps {
4  name: string;
5  control: Control<FieldValues>;
6  label: string;
7  rules?: object;
8  type?: string;
9}
10
11const ReusableTextField: React.FC<
12  ControlledTextFieldProps & TextFieldProps
13> = ({ name, control, label, rules, type, ...rest }) => {
14  return (
15    <Controller
16      name={name}
17      control={control}
18      rules={rules}
19      render={({ field, fieldState: { error } }) => (
20        <TextField
21          {...field}
22          {...rest}
23          label={label}
24          type={type}
25          error={!!error}
26          helperText={error ? error.message : ""}
27        />
28      )}
29    />
30  );
31};
32
33export default ReusableTextField;

The ReusableTextField component integrates a TextField with react-hook-form for validation and input handling. It renders a controlled text field with custom styling:

  • Props
    • name, control, label, rules, and optional type to configure the field.
  • Functionality
    • Uses Controller from react-hook-form to manage field state.
    • Displays validation errors via helperText when rules are violated.

This setup ensures reusable form fields with validation and consistent styling.

Output

Blog Image
Blog Image
Blog Image
Blog Image

Conclusion

In summary, a multi-step form enhances user experience by breaking down complex forms into more manageable sections. This approach not only simplifies the completion process for users but also makes the form easier to navigate and less overwhelming. Clear, logical progression between steps and a well-designed interface are key to maintaining a smooth and engaging user experience.

© 2026 IGNEK. All rights reserved.

Ignek on LinkedInIgnek on InstagramIgnek on FacebookIgnek on YouTubeIgnek on X