Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Horizontal Stepper
2.1.
Implementation
2.1.1.
Example
3.
Linear vs. Non-Linear Steppers
3.1.
Implementing Linear Stepper
3.2.
Example Code for Non-Linear Stepper
4.
Vertical Stepper
4.1.
Implementation
4.2.
Example
5.
Mobile Stepper
5.1.
Implementation
5.2.
Example
6.
MUI Stepper API: Syntax and Parameters
6.1.
Stepper Component Properties
6.2.
Step Component Properties
6.3.
MobileStepper Component Properties
7.
Creating a React Project
8.
Example: React MUI Linear Horizontal Stepper Navigation
8.1.
Example: React MUI Vertical Stepper Navigation
9.
Frequently Asked Questions 
9.1.
Can the MUI Stepper be used for forms with validation?
9.2.
How can I customize the look and feel of the MUI Stepper?
9.3.
Is it possible to dynamically add or remove steps in the MUI Stepper?
10.
Conclusion
Last Updated: Mar 27, 2024
Medium

React MUI Stepper

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

Material-UI (MUI) offers a wide range of components to create visually appealing and functionally rich user interfaces in React applications. Among these components is the Stepper, a versatile tool that enhances user experience by guiding them through sequential steps in a process. This component is especially useful in situations where a task requires multiple forms to be filled out or when showcasing a progression through different stages.

React MUI Stepper

The MUI Stepper component is highly customizable, offering several variants to suit different needs: Horizontal, Vertical, and Mobile Steppers. Each type serves a unique purpose and caters to different aspects of user interface design. In this article, we will delve into these variants, their APIs, and provide step-by-step guides on implementing them in a React project.

Horizontal Stepper

Overview

The Horizontal Stepper is the most common variant, displaying steps in a linear, horizontal line. It's ideal for desktop applications where space is not a constraint and where it's crucial to keep the user informed about their progress in a sequence of steps.

Implementation

To implement a Horizontal Stepper, you start by importing the necessary components from MUI, such as Stepper, Step, and StepLabel. Then, you define the steps in an array and use a map function to render each Step component. A typical setup involves managing the active step state and providing functionality to navigate through the steps.

Example

import React, { useState } from 'react';
import { Stepper, Step, StepLabel, Button } from '@mui/material';

const HorizontalStepper = () => {
    const [activeStep, setActiveStep] = useState(0);
    const steps = ['Step 1', 'Step 2', 'Step 3'];

    const handleNext = () => {
        setActiveStep((prevActiveStep) => prevActiveStep + 1);
    };

    const handleBack = () => {
        setActiveStep((prevActiveStep) => prevActiveStep - 1);
    };
    return (
        <div>
            <Stepper activeStep={activeStep}>
                {steps.map((label) => (
                    <Step key={label}>
                        <StepLabel>{label}</StepLabel>
                    </Step>
                ))}
            </Stepper>
            <div>
                {activeStep === steps.length ? (
                    <div>
                        All steps completed
                    </div>
                ) : (
                    <div>
                        <Button disabled={activeStep === 0} onClick={handleBack}>
                            Back
                        </Button>
                        <Button onClick={handleNext}>
                            Next
                        </Button>
                    </div>
                )}
            </div>
        </div>
    );
};

export default HorizontalStepper;

In this example, we have a basic horizontal stepper with three steps. The activeStep state determines the current active step, and the handleNext and handleBack functions manage the step navigation.

Also see,  React Native Reanimated

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Linear vs. Non-Linear Steppers

The Horizontal Stepper in MUI can be implemented as either linear or non-linear. The choice depends on the nature of the process you're guiding the user through.


Linear Stepper: This is the default mode. It requires users to complete each step before proceeding to the next. It's ideal for processes that require a sequential flow, like a checkout process or a multi-step form.


Non-Linear Stepper: In contrast, a non-linear stepper allows users to complete steps in any order. This flexibility is useful in scenarios where the steps are independent of each other, like a settings menu where users can choose which settings to adjust without a defined order.

Implementing Linear Stepper

In a linear stepper, you would typically check whether each step is completed before allowing the user to proceed to the next step. MUI's Stepper component supports this directly with the linear prop.

Example:

<Stepper activeStep={activeStep} linear>
    {/* Step components */}
</Stepper>


Implementing Non-Linear Stepper

For a non-linear stepper, the linear prop is not set, allowing users to jump between steps. You might provide buttons or other controls for each step to enable this.

Example:

<Stepper activeStep={activeStep}>
    {/* Step components */}
</Stepper>

Additional Components

StepButton: When using a non-linear stepper, StepButton can be used instead of StepLabel to make the step labels clickable, allowing users to jump to any step directly.
 

StepContent: For both linear and non-linear steppers, StepContent can be used to add more detailed content under each step, such as forms or instructions.

Example Code for Non-Linear Stepper

Here’s an example of implementing a non-linear stepper:

import React, { useState } from 'react';
import { Stepper, Step, StepButton, Button } from '@mui/material';

const NonLinearStepper = () => {
    const [activeStep, setActiveStep] = useState(0);
    const steps = ['Step 1', 'Step 2', 'Step 3'];

    const handleStep = (step) => () => {
        setActiveStep(step);
    };

    return (
        <div>
            <Stepper nonLinear activeStep={activeStep}>
                {steps.map((label, index) => (
                    <Step key={label}>
                        <StepButton onClick={handleStep(index)}>
                            {label}
                        </StepButton>
                    </Step>
                ))}
            </Stepper>
            {/* Additional step content */}
        </div>
    );
};
export default NonLinearStepper;

In this non-linear example, StepButton is used to make each step label clickable, allowing users to freely navigate between steps.

Vertical Stepper

Overview

The Vertical Stepper is another variant offered by MUI, designed for scenarios where vertical space is more abundant or preferable. It's particularly useful in mobile applications or web applications with a vertical layout. This stepper aligns the steps vertically, making it ideal for narrower screens or when a process involves more detailed step descriptions.

Implementation

The implementation of a Vertical Stepper is similar to that of the Horizontal Stepper, with the primary difference being the orientation of the steps. You will still use the Stepper, Step, and StepLabel components from MUI, but arrange them in a vertical format.

Example

import React, { useState } from 'react';
import { Stepper, Step, StepLabel, Button } from '@mui/material';

const VerticalStepper = () => {
    const [activeStep, setActiveStep] = useState(0);
    const steps = ['Step 1', 'Step 2', 'Step 3'];

    const handleNext = () => {
        setActiveStep((prevActiveStep) => prevActiveStep + 1);
    };

    const handleBack = () => {
        setActiveStep((prevActiveStep) => prevActiveStep - 1);
    };

    return (
        <div>
            <Stepper activeStep={activeStep} orientation="vertical">
                {steps.map((label) => (
                    <Step key={label}>
                        <StepLabel>{label}</StepLabel>
                    </Step>
                ))}
            </Stepper>
            <div>
                {activeStep === steps.length ? (
                    <div>
                        All steps completed
                    </div>
                ) : (
                    <div>
                        <Button disabled={activeStep === 0} onClick={handleBack}>
                            Back
                        </Button>
                        <Button onClick={handleNext}>
                            Next
                        </Button>
                    </div>
                )}
            </div>
        </div>
    );
};

export default VerticalStepper;

In this example, we set the orientation prop of the Stepper component to "vertical". This aligns the steps vertically. The rest of the implementation, including managing the active step and navigation, remains similar to the Horizontal Stepper.

Mobile Stepper

Overview

The Mobile Stepper in MUI is designed specifically for mobile applications or responsive web designs where screen real estate is limited. It provides a compact interface for stepping through different stages, often used in wizards, forms, or even for simple navigation through items like image galleries.

Implementation

Implementing a Mobile Stepper involves using the MobileStepper component from MUI. This component is typically used at the bottom of an application's screen and offers a variety of configurations such as progress dots, a progress bar, or simple text indicating the current step.

Example

import React, { useState } from 'react';
import { MobileStepper, Button } from '@mui/material';
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';

const DotsMobileStepper = () => {
    const [activeStep, setActiveStep] = useState(0);
    const maxSteps = 5;

    const handleNext = () => {
        setActiveStep((prevActiveStep) => prevActiveStep + 1);
    };

    const handleBack = () => {
        setActiveStep((prevActiveStep) => prevActiveStep - 1);
    };

    return (
        <div>
            <MobileStepper
                variant="dots"
                steps={maxSteps}
                position="static"
                activeStep={activeStep}
                nextButton={
                    <Button size="small" onClick={handleNext} disabled={activeStep === maxSteps - 1}>
                        Next
                        <KeyboardArrowRight />
                    </Button>
                }
                backButton={
                    <Button size="small" onClick={handleBack} disabled={activeStep === 0}>
                        <KeyboardArrowLeft />
                        Back
                    </Button>
                }
            />
        </div>
    );
};

export default DotsMobileStepper;

In this example, we're using the variant="dots" property to show progress through a series of dots. The MobileStepper component manages the active step and provides buttons to navigate forward and backward.

MUI Stepper API: Syntax and Parameters

Overview

The API for MUI's Stepper component is designed to provide flexibility and customization. It consists of several properties and methods that allow developers to tailor the stepper's behavior and appearance to fit their specific needs.

Stepper Component Properties

  • activeStep (number): Specifies the index of the active step.
     
  • alternativeLabel (boolean): Sets the labels for the steps to appear below the step icon rather than beside it. Useful for the horizontal stepper.
     
  • children (node): The content of the stepper, usually Step components.
     
  • connector (element): Customize the connector between the steps.
     
  • nonLinear (boolean): Allows non-linear navigation across steps.
     
  • orientation (string): The stepper orientation. Can be 'horizontal' or 'vertical'.

Step Component Properties

  • active (boolean): Marks the step as active.
     
  • completed (boolean): Marks the step as completed.
     
  • disabled (boolean): Disables the step.
     
  • children (node): The content of the step.


    StepLabel Component Properties
     
  • children (node): The label of the step.
     
  • error (boolean): If set, the step is marked as failed.
     
  • icon (node): Custom icon for the step.
     
  • optional (node): Optional text to display under the step label.

MobileStepper Component Properties

  • activeStep (number): The index of the active step.
     
  • backButton (node): A button element used for navigation to the previous step.
     
  • nextButton (node): A button element used for navigation to the next step.
     
  • position (string): Position of the stepper in the layout.
     
  • steps (number): Total number of steps.
     
  • variant (string): The design of the stepper - 'text', 'dots', or 'progress'.

Code Examples with API Usage

<Stepper activeStep={2} orientation="vertical">
    {/* Step components */}
</Stepper>

In this example, the activeStep prop is set to 2, and the orientation prop is set to "vertical", indicating a vertical stepper with the third step as the active one.

Creating a React Project

Creating a React project is a straightforward process, especially with the use of Create React App, a comfortable environment for learning React, and is the best way to start building a new single-page application in React.

Step 1: Install Node.js and npm

Before creating a React project, ensure you have Node.js and npm (Node Package Manager) installed on your system. npm is distributed with Node.js, which means that when you download Node.js, you automatically get npm installed on your computer.

Step 2: Create a New React App

Use the command line to create a new project. Type the following command:

npx create-react-app my-react-app


This creates a new React application named my-react-app. npx is a package runner tool that comes with npm 5.2+.

Step 3: Navigate to Your Project

Change directory to your new project:

cd my-react-app


Step 4: Start the Development Server

Run the following command to start the development server:

npm start


This will open a new browser window with your newly created React application.

Step 5: Install Material-UI Core and Icons

Since we'll be using MUI components, we need to add them to our project. Run:

npm install @mui/material @emotion/react @emotion/styled


And for icons:

npm install @mui/icons-material

Step 6: Create Your Components

Now, you can start creating your components. For our purposes, we will focus on implementing the MUI Stepper.

Example: React MUI Linear Horizontal Stepper Navigation

Implementation

Let's implement a linear horizontal stepper using React and MUI. This example will create a simple step-by-step navigation with three steps.

Step 1: Create Stepper Component

In your React project, create a new file for the stepper component, for example, LinearHorizontalStepper.js. Then, implement the stepper as follows:

import React, { useState } from 'react';
import { Stepper, Step, StepLabel, Button, Typography } from '@mui/material';

const LinearHorizontalStepper = () => {
    const [activeStep, setActiveStep] = useState(0);
    const steps = ['Step 1', 'Step 2', 'Step 3'];

    const handleNext = () => {
        setActiveStep((prevActiveStep) => prevActiveStep + 1);
    };

    const handleBack = () => {
        setActiveStep((prevActiveStep) => prevActiveStep - 1);
    };

    const handleReset = () => {
        setActiveStep(0);
    };
    return (
        <div>
            <Stepper activeStep={activeStep} alternativeLabel>
                {steps.map((label) => (
                    <Step key={label}>
                        <StepLabel>{label}</StepLabel>
                    </Step>
                ))}
            </Stepper>
            <div>
                {activeStep === steps.length ? (
                    <div>
                        <Typography>All steps completed</Typography>
                        <Button onClick={handleReset}>Reset</Button>
                    </div>
                ) : (
                    <div>
                        <Typography>Step {activeStep + 1}</Typography>
                        <div>
                            <Button disabled={activeStep === 0} onClick={handleBack}>
                                Back
                            </Button>
                            <Button onClick={handleNext}>
                                Next
                            </Button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};
export default LinearHorizontalStepper;

Step 2: Add to App.js

In your App.js, import and use the LinearHorizontalStepper component:

import React from 'react';
import LinearHorizontalStepper from './LinearHorizontalStepper';

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

export default App;

This code creates a linear horizontal stepper with three steps. Users can navigate through the steps using the Next and Back buttons. The stepper resets when all steps are completed.

Example: React MUI Vertical Stepper Navigation

Implementation

Now, let's implement a vertical stepper. This will be similar to the horizontal stepper but with a vertical orientation.

Step 1: Create Stepper Component

Create a file VerticalStepper.js and implement the component:

import React, { useState } from 'react';
import { Stepper, Step, StepLabel, Button, Typography } from '@mui/material';

const VerticalStepper = () => {
    const [activeStep, setActiveStep] = useState(0);
    const steps = ['Step 1', 'Step 2', 'Step 3'];

    const handleNext = () => {
        setActiveStep((prevActiveStep) => prevActiveStep + 1);
    };

    const handleBack = () => {
        setActiveStep((prevActiveStep) => prevActiveStep - 1);
    };

    return (
        <div>
            <Stepper activeStep={activeStep} orientation="vertical">
                {steps.map((label) => (
                    <Step key={label}>
                        <StepLabel>{label}</StepLabel>
                    </Step>
                ))}
            </Stepper>
            <div>
                {activeStep === steps.length ? (
                    <Typography>All steps completed</Typography>
                ) : (
                    <div>
                        <Typography>Step {activeStep + 1}</Typography>
                        <Button disabled={activeStep === 0} onClick={handleBack}>
                            Back
                        </Button>
                        <Button onClick={handleNext}>
                            Next
                        </Button>
                    </div>
                )}
            </div>
        </div>
    );
};
export default VerticalStepper;


Step 2: Add to App.js

Similarly, include the VerticalStepper in your App.js:

import React from 'react';
import VerticalStepper from './VerticalStepper';

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

export default App;

This component creates a vertical stepper, functioning similarly to the horizontal one but displayed vertically.

See More, React Native Paper, React devtools

Frequently Asked Questions 

Can the MUI Stepper be used for forms with validation?

Yes, the MUI Stepper can be effectively used in forms that require validation. In a linear stepper, you can validate the inputs of each step before allowing the user to proceed to the next one. This ensures that each part of the form is correctly filled out before moving on.

How can I customize the look and feel of the MUI Stepper?

MUI provides extensive customization options through its theming system. You can customize the appearance of the Stepper by using the sx prop for inline styles or by creating a custom theme and applying it using the ThemeProvider component. This allows you to change colors, spacing, sizes, and much more.

Is it possible to dynamically add or remove steps in the MUI Stepper?

Yes, the MUI Stepper supports dynamic addition and removal of steps. You can manage the steps as an array in your component's state and dynamically update this array based on user actions or other conditions. The Stepper component will automatically adjust to reflect the changes in the steps array.

Conclusion

In summary, the Material-UI Stepper in React provides an efficient and visually appealing way to guide users through multi-step processes. We delved into its various forms - Horizontal, Vertical, and Mobile - each tailored for different user interface scenarios. Through detailed examples, we demonstrated the implementation of both linear and non-linear steppers, underscoring their flexibility and adaptability. The MUI Stepper stands out as a crucial component for creating structured, interactive, and user-friendly navigation in web applications, proving itself as an invaluable tool for developers seeking to enhance user experience in complex processes. This exploration of the MUI Stepper not only highlights its utility but also showcases the robust capabilities of MUI in creating sophisticated and intuitive UI components.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
useImperativeHandle
Next article
React Native Calendars
Live masterclass