This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Building Multi-Step Forms in React

  • ReactJS
  • September 20, 2024

Share On :

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.

folder-structure
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.

				
					//Create react app using the following command
npx create-react-app multistep-form --template typescript

//Install the required library
npm i react-hook-form
npm install @mui/material
npm 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.
				
					// App.tsx

import MultiStepFormController from "./components/MultiStepFormController";

const App = () = > {
  return (<div style = {{width : "100%"}}><MultiStepFormController /></ div>);
};

export 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.

				
					//MultiStepFormController.tsx

export interface IFormData {
  firstName?: string;
  lastName?: string;
  age?: number | null;
  email?: string;
  contactNo?: number | null;
  city?: string;
  country?: string;
  zipCode?: number | null;
}

const initialFormData: IFormData = {
  firstName: "",
  lastName: "",
  age: 0,
  email: "",
  contactNo: 0,
  city: "",
  country: "",
  zipCode: 0,
};

const MultiStepFormController = () => {
  const [formData, setFormData] = useState<IFormData>(initialFormData);
  const [step, setStep] = useState<number>(1);

  let currentContent: JSX.Element | undefined;

  switch (step) {
    case 1:
      currentContent = (
        <MultiStepForm
          currentStep={step}
          setStep={setStep}
          setFormData={setFormData}
          formData={{
            firstName: initialFormData.firstName,
            lastName: initialFormData.lastName,
            age: initialFormData.age,
          }}
        />
      );
      break;
    case 2:
      currentContent = (
        <MultiStepForm
          currentStep={step}
          setStep={setStep}
          setFormData={setFormData}
          formData={{
            email: initialFormData.email,
            contactNo: initialFormData.contactNo,
          }}
        />
      );
      break;
    case 3:
      currentContent = (
        <MultiStepForm
          currentStep={step}
          setStep={setStep}
          setFormData={setFormData}
          formData={{
            city: initialFormData.city,
            country: initialFormData.country,
            zipCode: initialFormData.zipCode,
          }}
        />
      );
      break;
    default:
      currentContent = (
        <Box>
          <Box>
            <Typography>
              Your details have been submitted successfully!
            </Typography>

            <Grid container spacing={2}>
              //Rendering Submitted Form Data
            </Grid>
          </Box>
        </Box>
      );
  }

  return <>{currentContent}</>;
};

export 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.

				
					//MultistepForm.tsx

interface IMultistepForm {
  formData: IFormData;
  setFormData: React.Dispatch<React.SetStateAction<IFormData>>;
  currentStep: number;
  setStep: React.Dispatch<React.SetStateAction<number>>;
}

const steps = [
  "Personal Information",
  "Contact Information",
  "Location Details",
];

const MultistepForm: React.FC<IMultistepForm> = ({
  formData,
  setFormData,
  currentStep,
  setStep,
}) => {
  const {
    handleSubmit,
    control,
    formState: { errors },
    getValues,
  } = useForm<IFormData>({
    defaultValues: formData,
  });

  const handleNextStep = (data: IFormData) => {
    setFormData((prevData) => ({ ...prevData, ...data }));
    setStep((step) => step + 1);
  };

  const handleBackStep = () => {
    setStep((step) => step - 1);
  };

  const onSubmit = (data: IFormData) => {
    setStep((step) => step + 1);
    setFormData((prevData) => ({ ...prevData, ...data }));
    console.log("Final Data Submitted:", getValues());
  };

  return (
    <Box>
      <Box>
        <Stepper activeStep={currentStep - 1}>
          {steps.map((label, index) => (
            <Step key={index}>
              <StepLabel>
                <Typography>{label}</Typography>
              </StepLabel>
            </Step>
          ))}
        </Stepper>
        <form
          onSubmit={handleSubmit(currentStep === 3 ? onSubmit : handleNextStep)}
        >
          {currentStep === 1 && (
            <>
              <ReusableTextField
                name="firstName"
                control={control}
                label="First Name"
                rules={{ required: "First name is required" }}
              />
              <ReusableTextField
                name="lastName"
                control={control}
                label="Last Name"
              />
              <ReusableTextField
                name="age"
                control={control}
                label="Age"
                type="number"
              />
            </>
          )}
          {currentStep === 2 && (
            <>
              <ReusableTextField
                name="email"
                control={control}
                label="Email"
                rules={{ required: "Email is required" }}
              />
              <ReusableTextField
                name="contactNo"
                control={control}
                label="Contact No"
                type="number"
              />
            </>
          )}
          {currentStep === 3 && (
            <>
              <ReusableTextField name="city" control={control} label="City" />
              <ReusableTextField
                name="country"
                control={control}
                label="Country"
              />
              <ReusableTextField
                name="zipCode"
                control={control}
                label="Zip Code"
                type="number"
              />
            </>
          )}
          <Box>
            {currentStep > 1 && <Button>Back</Button>}
            <Button variant="contained" type="submit">
              {currentStep === 3 ? "Submit" : "Next"}
            </Button>
          </Box>
        </form>
      </Box>
    </Box>
  );
};

export 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.

				
					//ReusableTextField.tsx

interface ControlledTextFieldProps {
  name: string;
  control: Control<FieldValues>;
  label: string;
  rules?: object;
  type?: string;
}

const ReusableTextField: React.FC<
  ControlledTextFieldProps & TextFieldProps
> = ({ name, control, label, rules, type, ...rest }) => {
  return (
    <Controller
      name={name}
      control={control}
      rules={rules}
      render={({ field, fieldState: { error } }) => (
        <TextField
          {...field}
          {...rest}
          label={label}
          type={type}
          error={!!error}
          helperText={error ? error.message : ""}
        />
      )}
    />
  );
};

export 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
output1
output2
output3
output4
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.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

July 19, 2024
Simplifying State with Context API
Simplifying State with Context API
September 6, 2024
Creating forms in React with React Hook Form
Creating forms in React with React Hook Form
September 6, 2024
Creating forms in React with Formik
Creating forms in React with Formik
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 4, 2023
Telemedicine Appointment & Health Record Portal
Telemedicine Appointment & Health Record Portal

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram