Creating a Multi-Step Form in React

Introduction

Multi-step forms enhance user experience by breaking down long forms into smaller sections. This approach reduces user fatigue and can improve form completion rates. We will create a multi-step form with React that collects user information over several steps and then submits the data.

1. Setting Up the React Project

First, set up a new React project using the Create React App.

npx create-react-app multi-step-form
cd multi-step-form
npm start

2. Structuring the Multi-Step Form

We'll divide our form into several components, one for each step and a main component to handle navigation and state.

  1. Create Components for Each Step
    • Step1.js
    • Step2.js
    • Step3.js
    • Confirmation.js
    • Success.js
  2. Create a Main Form Component
    • MultiStepForm.js

Step 1. js

import React from 'react';

const Step1 = ({ nextStep, handleChange, values }) => {
  return (
    <div>
      <h2>Step 1: Personal Details</h2>
      <label>
        First Name:
        <input
          type="text"
          name="firstName"
          value={values.firstName}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Last Name:
        <input
          type="text"
          name="lastName"
          value={values.lastName}
          onChange={handleChange}
        />
      </label>
      <br />
      <button onClick={nextStep}>Next</button>
    </div>
  );
};

export default Step1;

Step 2. js

import React from 'react';

const Step2 = ({ nextStep, prevStep, handleChange, values }) => {
  return (
    <div>
      <h2>Step 2: Contact Details</h2>
      <label>
        Email:
        <input
          type="email"
          name="email"
          value={values.email}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Phone Number:
        <input
          type="tel"
          name="phone"
          value={values.phone}
          onChange={handleChange}
        />
      </label>
      <br />
      <button onClick={prevStep}>Back</button>
      <button onClick={nextStep}>Next</button>
    </div>
  );
};

export default Step2;

Step 3. js

import React from 'react';

const Step3 = ({ nextStep, prevStep, handleChange, values }) => {
  return (
    <div>
      <h2>Step 3: Address Details</h2>
      <label>
        Address:
        <input
          type="text"
          name="address"
          value={values.address}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        City:
        <input
          type="text"
          name="city"
          value={values.city}
          onChange={handleChange}
        />
      </label>
      <br />
      <button onClick={prevStep}>Back</button>
      <button onClick={nextStep}>Next</button>
    </div>
  );
};

export default Step3;

Confirmation.js

import React from 'react';

const Confirmation = ({ prevStep, values, handleSubmit }) => {
  return (
    <div>
      <h2>Confirmation</h2>
      <ul>
        <li>First Name: {values.firstName}</li>
        <li>Last Name: {values.lastName}</li>
        <li>Email: {values.email}</li>
        <li>Phone: {values.phone}</li>
        <li>Address: {values.address}</li>
        <li>City: {values.city}</li>
      </ul>
      <button onClick={prevStep}>Back</button>
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
};

export default Confirmation;

Success.js

import React from 'react';

const Success = () => {
  return (
    <div>
      <h2>Success!</h2>
      <p>Your information has been submitted successfully.</p>
    </div>
  );
};

export default Success;

App.Js

import React from 'react';
import MultiStepForm from './MultiStepForm';
import './App.css';

function App() {
  return (
    <div className="App">
      <MultiStepForm />
    </div>
  );
}

export default App;

3. Managing State with React Hooks


MultiStepForm.js

import React, { useState } from 'react';
import Step1 from './Step1';
import Step2 from './Step2';
import Step3 from './Step3';
import Confirmation from './Confirmation';
import Success from './Success';

const MultiStepForm = () => {
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    address: '',
    city: ''
  });

  const nextStep = () => {
    setStep(step + 1);
  };

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

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSubmit = () => {
    // Handle form submission, e.g., send data to an API
    nextStep();
  };

  switch (step) {
    case 1:
      return <Step1 nextStep={nextStep} handleChange={handleChange} values={formData} />;
    case 2:
      return <Step2 nextStep={nextStep} prevStep={prevStep} handleChange={handleChange} values={formData} />;
    case 3:
      return <Step3 nextStep={nextStep} prevStep={prevStep} handleChange={handleChange} values={formData} />;
    case 4:
      return <Confirmation prevStep={prevStep} values={formData} handleSubmit={handleSubmit} />;
    case 5:
      return <Success />;
    default:
      return <Step1 nextStep={nextStep} handleChange={handleChange} values={formData} />;
  }
};

export default MultiStepForm;

4. Implementing Navigation Between Steps

In the MultiStepForm component, we handle navigation by updating the step state using the nextStep and prevStep functions. Each step renders a different component based on the current step value.

5. Handling Form Submission

In the handleSubmit function, you can add the logic to submit the form data to an API or handle it as needed. After submission, we move to the success screen by calling nextStep.

6. Adding Validation

For validation, you can add validation logic within each step component or in the main form component before moving to the next step. Libraries like Yup and Formik can simplify validation.

7. Styling the Form

Add some basic CSS to style the form components. Create a styles.css file and import it into your main component.

styles.css

body {
  font-family: Arial, sans-serif;
}

h2 {
  color: #333;
}

form {
  background-color: #f2f2f2;
  padding: 20px;
  border-radius: 5px;
}

label {
  display: block;
  margin-bottom: 8px;
}

input {
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

Import the CSS in MultiStepForm.js

import './styles.css';

Details

Summary

You've now created a multi-step form in React! This form guides users through a sequence of steps, collects data, and handles form submissions. You can further enhance this form by adding more steps, improving validation, or integrating with a backend service.

This project demonstrates how React's component-based architecture and hooks make it easy to build interactive, user-friendly forms.

Happy coding!