How To Build A MUI Stepper That Enhances Functionality

Web developers often find themselves tasked with crafting web application interfaces that include a rich array of UI elements, from buttons and tabs to sliders, toggle buttons, and dropdowns. In certain cases, these interfaces are designed to guide users through multi-step processes, akin to those found in reservation and booking systems. These multi-step workflows are typically decomposed into discrete stages, such as gathering user information, processing payments, and confirming bookings.

In the world of web development, these progress-tracking components are commonly known as ‘stepper components’. In this guide, we explore how to create a React Stepper with the Material UI Stepper Component. You’ll find practical examples and step-by-step instructions to seamlessly integrate this powerful tool into your React applications. As a result, you’ll enhance user experience and functionality.

PS: Engineers waste time building and styling components when working on a project. Writing repetitive markup adds time to the project and is a mundane, boring task for engineers. PureCode.ai uses AI to generate a large selection of custom, styled UI components for different projects and component types.

What is a Stepper?

A Stepper is a fundamental component that effectively visualizes a multi-step process. It enables users to track their progress as they navigate through the workflow. It serves as a valuable tool for displaying and managing workflow progress, often requiring programmatic transitions between form segments.

Steppers communicate progress through logical and numbered steps, delivering a wizard-like workflow. They effectively break down a sequence into logical and numbered steps. This makes them invaluable not only for guiding users but also for facilitating navigation. Additionally, Steppers can offer transient feedback messages upon completing a step, further enhancing user interaction.

Steppers find practical applications in numerous real-world scenarios, significantly improving user experience by guiding individuals through multi-step processes. In e-commerce, they facilitate smooth checkout experiences, ensuring users navigate through shipping details, payment methods, and order reviews systematically.

Amazon Checkout Form with Steppers

User registration processes on websites can also benefit from steppers, breaking down the setup into manageable sections for efficient completion. Software installations and booking systems for flights or hotels can also leverage steppers to simplify complex procedures, leading users through essential configurations and choices.

Software Installation with Steppers

Additionally, productivity apps utilize task wizards with steppers. Some practical use includes guiding users sequentially through intricate document or project creation, and promoting a structured and user-friendly workflow across various real-world scenarios.

Types of Steps

  • Editable steps: Editable steps empower users to revisit and modify completed steps, making them ideal for workflows requiring in-session editing.

  • Non-editable steps: These steps prevent users from making further edits, reducing the risk of distractions and ensuring seamless form completion.

  • Mobile Steps: Designed for mobile devices, these steps ensure a smooth and responsive user experience on smaller screens.

  • Optional Steps: In linear flows, optional steps are marked as such, offering users flexibility in their navigation and interaction.

Ways to Implement Stepper Components in React with Material UI

You can incorporate Stepper Components in your React application with Material UI using the following four approaches:

  • Horizontal: This method displays steps horizontally, making them ideal for guiding users through a linear, sequential process.

  • Vertical: Vertical Steppers arrange steps in a column, providing a convenient layout for applications that require a vertically oriented flow.

  • Linear: Linear Steppers enforce a strict progression order, ensuring users complete steps in a predefined sequence.

  • Non-linear: In contrast, Non-linear Steppers allow users to navigate steps freely, useful for workflows with optional or non-sequential elements.

Now that you’ve seen the different ways in which steppers can be created in React using Material UI, let’s take a deep dive and build some steppers using the above-mentioned methods.

Horizontal Stepper Component

Horizontal steppers excel in situations where the content of one step relies on the completion of a prior step. They prominently display step names and numbers on a horizontal bar, which can be conveniently fixed to the top of the page as users scroll down. To maintain a smooth user experience, it’s wise to use concise step names.

Before we delve into building one, let’s first explore how to import the Material UI stepper component.

Importing Stepper Components from Material UI

import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepLabel from '@mui/material/StepLabel';

These components are part of the Material-UI library in React and are used to create a stepper, a user interface element that guides users through a series of steps or stages in a linear or non-linear progression, such as a multi-step form or a wizard.

  1. `Stepper`: This component serves as the container for the entire stepper. It manages the state of the current step and controls the flow of the stepper. You can specify various properties that affect the overall appearance and behavior of the stepper. Including the active step and orientation (horizontal or vertical).
  2. `Step`: The `Step` component represents an individual step within the stepper. It defines the content and behaviour of a specific step. For example, what should be displayed during an active step. You can set properties like a label or icon for each step, which are typically displayed in the stepper for navigation.
  3. `StepLabel`: The `StepLabel` component displays the label or title for each step in the stepper. It is often used within the `Step` component to provide a description or title for the step. You can customize the appearance and style of the label using this component.

These components work together to create a structured and visually clear way to guide users through a series of steps, making it easier to complete a process or form, especially when it involves multiple stages. The `Stepper` manages the overall flow, `Step` defines the content for each step, and `StepLabel` helps label and describe each step in the sequence.

Building a Linear Horizontal Stepper

We’ve seen the components that create the stepper component when combined. Let’s take a look at an example where we create a linear horizontal stepper.

Linear steppers require users to complete one step before they can proceed to the next. We will demonstrate how to control the stepper using the `activeStep` prop and set the stepper orientation using the `orientation` prop.

Additionally, we’ll include an optional step and show how to handle skipped steps. But before we begin, let’s import all the other components that we’ll be putting together to create this linear horizontal stepper.

import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepLabel from '@mui/material/StepLabel';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';

Next, we define an array of step labels and initialize the component.

const steps = ['Select campaign settings', 'Create an ad group', 'Create an ad'];

export default function HorizontalLinearStepper() {
  const [activeStep, setActiveStep] = React.useState(0);
  const [skipped, setSkipped] = React.useState(new Set());

  return();
}

We determine whether a step is optional and whether it has been skipped.

export default function HorizontalLinearStepper() {
  //...

  const isStepOptional = (step) => {
    return step === 1;
  };

  const isStepSkipped = (step) => {
    return skipped.has(step);
  };

  return();
}

Next, we define functions to handle moving to the next step, going back, skipping optional steps, and resetting the stepper.

export default function HorizontalLinearStepper() {
  //...

  const handleNext = () => {
    let newSkipped = skipped;
    if (isStepSkipped(activeStep)) {
      newSkipped = new Set(newSkipped.values());
      newSkipped.delete(activeStep);
    }

    setActiveStep((prevActiveStep) => prevActiveStep + 1);
    setSkipped(newSkipped);
  };

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

  const handleSkip = () => {
    if (!isStepOptional(activeStep)) {
      // You probably want to guard against something like this,
      // it should never occur unless someone's actively trying to break something.
      throw new Error("You can't skip a step that isn't optional.");
    }

    setActiveStep((prevActiveStep) => prevActiveStep + 1);
    setSkipped((prevSkipped) => {
      const newSkipped = new Set(prevSkipped.values());
      newSkipped.add(activeStep);
      return newSkipped;
    });
  };

  const handleReset = () => {
    setActiveStep(0);
  };

  return();
}

We then return the JSX for the stepper, including step labels and buttons for navigation.

export default function HorizontalLinearStepper() {
  //...

  return (
    <Box sx={{ width: '100%' }}>
      <Stepper activeStep={activeStep}>
        {steps.map((label, index) => {
          const stepProps = {};
          const labelProps = {};
          if (isStepOptional(index)) {
            labelProps.optional = (
              <Typography variant="caption">Optional</Typography>
            );
          }
          if (isStepSkipped(index)) {
            stepProps.completed = false;
          }
          return (
            <Step key={label} {...stepProps}>
              <StepLabel {...labelProps}>{label}</StepLabel>
            </Step>
          );
        })}
      </Stepper>
      {activeStep === steps.length ? (
        <React.Fragment>
          <Typography sx={{ mt: 2, mb: 1 }}>
            All steps completed - you&apos;re finished
          </Typography>
          <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
            <Box sx={{ flex: '1 1 auto' }} />
            <Button onClick={handleReset}>Reset</Button>
          </Box>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <Typography sx={{ mt: 2, mb: 1 }}>Step {activeStep + 1}</Typography>
          <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
            <Button
              color="inherit"
              disabled={activeStep === 0}
              onClick={handleBack}
              sx={{ mr: 1 }}
            >
              Back
            </Button>
            <Box sx={{ flex: '1 1 auto' }} />
            {isStepOptional(activeStep) && (
              <Button color="inherit" onClick={handleSkip} sx={{ mr: 1 }}>
                Skip
              </Button>
            )}

            <Button onClick={handleNext}>
              {activeStep === steps.length - 1 ? 'Finish' : 'Next'}
            </Button>
          </Box>
        </React.Fragment>
      )}
    </Box>
  );
}

After putting together all that code, here’s what the linear horizontal stepper will look like when viewed on the browser.

Linear Horizontal Stepper

Building a Non-linear Horizontal Stepper

Now, let’s move on to building a non-linear horizontal stepper. But before that, let’s recap on how non-linear horizontal components are different from linear ones. Non-linear horizontal steppers offer users the flexibility to enter a multi-step flow at any point in the process.

This code example below showcases a variation of the standard horizontal stepper, but with a key difference: steps are not automatically disabled based on the `activeStep` prop. Instead, we utilize the `StepButton` component to make step labels clickable and set the completed flag.

As steps can be accessed in a non-linear fashion, it becomes your responsibility to determine when all steps are completed, or if they need to be completed.

import * as React from 'react';
import Box from '@mui/material/Box';
import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepButton from '@mui/material/StepButton';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';

const steps = ['Select campaign settings', 'Create an ad group', 'Create an ad'];

export default function HorizontalNonLinearStepper() {
  const [activeStep, setActiveStep] = React.useState(0);
  const [completed, setCompleted] = React.useState({});

  const totalSteps = () => {
    return steps.length;
  };

  const completedSteps = () => {
    return Object.keys(completed).length;
  };

  const isLastStep = () => {
    return activeStep === totalSteps() - 1;
  };

  const allStepsCompleted = () => {
    return completedSteps() === totalSteps();
  };

  const handleNext = () => {
    const newActiveStep =
      isLastStep() && !allStepsCompleted()
        ? // It's the last step, but not all steps have been completed,
          // find the first step that has been completed
          steps.findIndex((step, i) => !(i in completed))
        : activeStep + 1;
    setActiveStep(newActiveStep);
  };

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

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

  const handleComplete = () => {
    const newCompleted = completed;
    newCompleted[activeStep] = true;
    setCompleted(newCompleted);
    handleNext();
  };

  const handleReset = () => {
    setActiveStep(0);
    setCompleted({});
  };

  return (
    <Box sx={{ width: '100%' }}>
      <Stepper nonLinear activeStep={activeStep}>
        {steps.map((label, index) => (
          <Step key={label} completed={completed[index]}>
            <StepButton color="inherit" onClick={handleStep(index)}>
              {label}
            </StepButton>
          </Step>
        ))}
      </Stepper>
      <div>
        {allStepsCompleted() ? (
          <React.Fragment>
            <Typography sx={{ mt: 2, mb: 1 }}>
              All steps completed - you&apos;re finished
            </Typography>
            <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
              <Box sx={{ flex: '1 1 auto' }} />
              <Button onClick={handleReset}>Reset</Button>
            </Box>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <Typography sx={{ mt: 2, mb: 1, py: 1 }}>
              Step {activeStep + 1}
            </Typography>
            <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
              <Button
                color="inherit"
                disabled={activeStep === 0}
                onClick={handleBack}
                sx={{ mr: 1 }}
              >
                Back
              </Button>
              <Box sx={{ flex: '1 1 auto' }} />
              <Button onClick={handleNext} sx={{ mr: 1 }}>
                Next
              </Button>
              {activeStep !== steps.length &&
                (completed[activeStep] ? (
                  <Typography variant="caption" sx={{ display: 'inline-block' }}>
                    Step {activeStep + 1} already completed
                  </Typography>
                ) : (
                  <Button onClick={handleComplete}>
                    {completedSteps() === totalSteps() - 1
                      ? 'Finish'
                      : 'Complete Step'}
                  </Button>
                ))}
            </Box>
          </React.Fragment>
        )}
      </div>
    </Box>
  );
}

This is what the result of the above code example should look like. You’ll notice there’s a “next” button now which gives users the ability to move or skip to the next step on the stepper component, unlike the linear stepper component.

Non-linear Horizontal Stepper

Adding Alternative Label to Material UI Stepper

We can also add a distinctive touch to the Material UI Stepper by positioning labels below the step icons. This can be achieved by setting the `alternativeLabel` prop on the Stepper component.

import * as React from 'react';
import Box from '@mui/material/Box';
import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepLabel from '@mui/material/StepLabel';

const steps = [
  'Select master blaster campaign settings',
  'Create an ad group',
  'Create an ad',
];

export default function HorizontalLinearAlternativeLabelStepper() {
  return (
    <Box sx={{ width: '100%' }}>
      <Stepper activeStep={1} alternativeLabel>
        {steps.map((label) => (
          <Step key={label}>
            <StepLabel>{label}</StepLabel>
          </Step>
        ))}
      </Stepper>
    </Box>
  );
}

By incorporating the `alternativeLabel` prop as seen in the code snippet above, you can create a visual distinction in your Stepper, placing labels below the step icons for improved aesthetics and clarity.

Alternative Label

Creating an Error Step

Creating an error step in a stepper component becomes valuable when you want to clearly indicate and manage errors or exceptional conditions during a multi-step process. This feature is especially useful in scenarios involving user input or form submissions where validation failures may occur.

By marking the step with errors, users receive immediate feedback on where issues occurred. This aids them in correcting mistakes or fulfilling specific conditions.

The provided code sandbox below demonstrates how to create a horizontal stepper with an error step using Material-UI components in a React application.

This code sandbox showcases a scenario where one of the steps is marked as an error step and includes an alert message. Let’s break down how this code achieves that:

  1. Import Statements: The code begins with import statements, bringing in the necessary components and styles from the Material-UI library.

  2. Step Labels: An array called `steps` is defined, containing labels for each step in the stepper. These labels represent the various stages of a process.

  3. Functional Component: The code defines a functional component named `HorizontalStepperWithError`. This component is used to render the stepper with an error step.

  4. `isStepFailed` Function: Inside the component, there’s a function called `isStepFailed(step)`, which returns `true` for a specific step, in this case, step 1. This function is used to determine which step should be marked as having an error.

  5. Stepper Component: Within the component, a `Stepper` component is created with `activeStep` set to 1. This means that the second step (index 1) will be marked as the active step when the stepper is rendered.

Breakdown Part 2

  1. Mapping Steps: The `steps` array is mapped over, and for each step, the code checks whether it’s the error step. If the current step is the error step (in this case, step 1), additional properties are added to the `StepLabel`.

  2. `labelProps`: An object called `labelProps` is created to hold the properties to be applied to the `StepLabel`. If the step is the error step, it adds an optional message with red error text (using the `color=”error”` attribute).

  3. `error` Prop: The `error` prop is set to `true` for the error step’s `StepLabel`. This prop visually highlights the step as having an error by changing its appearance (e.g., adding a red border or icon).

  4. Rendering: The `StepLabel` component for each step is rendered within the `Stepper`, and the `labelProps` object is spread to apply the error-related properties to the appropriate step.

The result is a horizontal stepper where the second step is marked with an error message and an indication of an error, making it visually distinct from the other steps. This can be useful for highlighting a step that requires the user’s attention or where an error has occurred in the process.

Creating a Customized Horizontal Stepper

In this section, we’ll demonstrate how to create a customized horizontal stepper with Material-UI. This customization includes defining alternative connectors and unique step icons for a visually appealing and distinct stepper.

The code sandbox below imports the necessary components and styles to build the customized stepper. It also sets up two different connectors: `QontoConnector` and `ColorlibConnector`, and their respective step icons: `QontoStepIcon` and `ColorlibStepIcon`.

For the `QontoConnector`, the connector is adjusted to be displayed at the top of the step labels. Additionally, the active and completed step lines are styled with different colors.

In the `QontoStepIcon`, step icons are customized to display a checkmark for completed steps and a circle for active steps.

The `ColorlibConnector` includes a colorful gradient to signify active and completed steps, creating a distinct visual effect.

In the `ColorlibStepIcon`, specific icons are associated with each step, and the step’s appearance is enhanced when it’s active or completed.

Finally, the customized steppers are rendered within a `Stack` component. The `StepLabel` component utilizes the custom `StepIconComponent` for each step, enabling the unique styling and icons for a visually enriched user experience.

Horizontal Stepper: Additional Thoughts

This example highlights how Material-UI empowers you to create personalized steppers, allowing you to tailor the user interface to your specific needs and design preferences. Custom connectors and step icons can help make your application’s stepper stand out and offer a unique user experience. For further details on customization, you can refer to the overrides documentation page.

By using these customization options, you can make your horizontal steppers not only functional but also visually appealing and in line with your application’s design guidelines.

With PureCode.ai you can get customized, and ready-to-use components which will allow you to prioritize more important and thought-intensive tasks to speed up the development of your user interface. PureCode.ai can cater for your code development process which will save you valuable time and effort when working on a project.

Vertical Stepper Component

Vertical steppers are thoughtfully designed for narrower screen sizes, making them particularly well-suited for mobile devices. They offer the same rich functionality and feature set as their horizontal counterparts.

In the provided code sandbox, a React component is showcased to demonstrate the usage of a vertical linear stepper. It’s an ideal choice when you need to guide users through a series of steps, especially on smaller screens.

The above code sandbox includes the setup for the vertical linear stepper. It defines each step with a label and a detailed description to guide users effectively. Users can progress through the steps by clicking the “Continue” button and navigating back using the “Back” button. When all steps are completed, a “Finish” button is displayed, indicating successful completion.

By utilizing this vertical linear stepper, you can create a user-friendly and responsive interface, ensuring a seamless experience on mobile devices and narrow screens. This component simplifies complex processes, making them manageable and easy to follow step by step.

Performance

In Material-UI Steppers, each step’s content is unmounted when it’s closed, which is a performance optimization technique. However, in some cases, you may want to keep the step’s content mounted for various reasons:

  1. Search Engine Accessibility: If you need the content to be accessible to search engines for SEO purposes, you should consider keeping it mounted.

  2. Rendering Complex Components: In scenarios where you have expensive or complex component trees within your step, maintaining the step’s content mounted ensures a more responsive user interaction. This can be beneficial when optimizing for user experience and responsiveness.

To achieve this, you can set the `unmountOnExit` property to `false` in the `StepContent` component like this:

<StepContent TransitionProps={{ unmountOnExit: false }} />

By making this adjustment, you ensure that the step’s content remains mounted even when it’s closed, which can be advantageous for specific use cases where search engine accessibility or improved interaction responsiveness is a priority.

Mobile Stepper

The Mobile Stepper is a specialized component designed for optimal use on mobile devices. It offers a compact and space-efficient solution for guiding users through a series of steps. While it may have fewer features compared to the vertical stepper, it excels in its mobile-friendly design. See mobile steps for their inspiration.

It provides three distinct variants for displaying the progress through the available steps:

  1. Text: Utilizes text labels to indicate step progress.

  2. Dots: Employs dot-based markers to represent step progression.

  3. Progress: Uses a linear progress bar to visually track step completion.

Let’s take a deeper dive into these variants, and let’s see them in action with some code examples.

Text

The Text Mobile Stepper is an excellent choice when you want a clear and concise representation of the current step and the total number of steps.

import * as React from 'react';
import Box from '@mui/material/Box';
import { useTheme } from '@mui/material/styles';
import MobileStepper from '@mui/material/MobileStepper';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';

const steps = [
  {
    label: 'Select campaign settings',
    description: `For each ad campaign that you create, you can control how much
              you're willing to spend on clicks and conversions, which networks
              and geographical locations you want your ads to show on, and more.`,
  },
  {
    label: 'Create an ad group',
    description:
      'An ad group contains one or more ads which target a shared set of keywords.',
  },
  {
    label: 'Create an ad',
    description: `Try out different ad text to see what brings in the most customers,
              and learn how to enhance your ads using features like ad extensions.
              If you run into any problems with your ads, find out how to tell if
              they're running and how to resolve approval issues.`,
  },
];

export default function TextMobileStepper() {
  const theme = useTheme();
  const [activeStep, setActiveStep] = React.useState(0);
  const maxSteps = steps.length;

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

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

  return (
    <Box sx={{ maxWidth: 400, flexGrow: 1 }}>
      <Paper
        square
        elevation={0}
        sx={{
          display: 'flex',
          alignItems: 'center',
          height: 50,
          pl: 2,
          bgcolor: 'background.default',
        }}
      >
        <Typography>{steps[activeStep].label}</Typography>
      </Paper>
      <Box sx={{ height: 255, maxWidth: 400, width: '100%', p: 2 }}>
        {steps[activeStep].description}
      </Box>
      <MobileStepper
        variant="text"
        steps={maxSteps}
        position="static"
        activeStep={activeStep}
        nextButton={
          <Button
            size="small"
            onClick={handleNext}
            disabled={activeStep === maxSteps - 1}
          >
            Next
            {theme.direction === 'rtl' ? (
              <KeyboardArrowLeft />
            ) : (
              <KeyboardArrowRight />
            )}
          </Button>
        }
        backButton={
          <Button size="small" onClick={handleBack} disabled={activeStep === 0}>
            {theme.direction === 'rtl' ? (
              <KeyboardArrowRight />
            ) : (
              <KeyboardArrowLeft />
            )}
            Back
          </Button>
        }
      />
    </Box>
  );
}

This example showcases a mobile stepper using the “Text” variant, designed to provide step progress information in a textual format.

MUI Text Mobile Stepper

Text with Carousel Effect

The Text Variant Mobile Stepper with Carousel provides an engaging way to guide users through a sequence of steps while presenting them with captivating images.

This example demonstrates a mobile stepper using the “Text” variant, enhanced with a carousel effect using react-swipeable-views.

This Text Variant Mobile Stepper with a Carousel Effect is a versatile tool for creating visually appealing step-by-step guides with user-friendly navigation.

Dots

The Dots Variant Mobile Stepper is ideal for scenarios where the number of steps is limited, making it easy for users to visualize their progress through a sequence. This example showcases a mobile stepper with the “Dots” variant.

import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import MobileStepper from '@mui/material/MobileStepper';
import Button from '@mui/material/Button';
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';

export default function DotsMobileStepper() {
  const theme = useTheme();
  const [activeStep, setActiveStep] = React.useState(0);

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

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

  return (
    <MobileStepper
      variant="dots"
      steps={6}
      position="static"
      activeStep={activeStep}
      sx={{ maxWidth: 400, flexGrow: 1 }}
      nextButton={
        <Button size="small" onClick={handleNext} disabled={activeStep === 5}>
          Next
          {theme.direction === 'rtl' ? (
            <KeyboardArrowLeft />
          ) : (
            <KeyboardArrowRight />
          )}
        </Button>
      }
      backButton={
        <Button size="small" onClick={handleBack} disabled={activeStep === 0}>
          {theme.direction === 'rtl' ? (
            <KeyboardArrowRight />
          ) : (
            <KeyboardArrowLeft />
          )}
          Back
        </Button>
      }
    />
  );
}

The Dots Variant Mobile Stepper is a user-friendly navigation tool, particularly suitable when there are a small number of steps to display.

MUI Dots Variant Mobile Stepper

Progress

The Progress Variant Mobile Stepper is suitable when you have numerous steps or if new steps need to be inserted dynamically based on user responses to previous steps. This example demonstrates a mobile stepper with the “Progress” variant.

import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import MobileStepper from '@mui/material/MobileStepper';
import Button from '@mui/material/Button';
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';

export default function ProgressMobileStepper() {
  const theme = useTheme();
  const [activeStep, setActiveStep] = React.useState(0);

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

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

  return (
    <MobileStepper
      variant="progress"
      steps={6}
      position="static"
      activeStep={activeStep}
      sx={{ maxWidth: 400, flexGrow: 1 }}
      nextButton={
        <Button size="small" onClick={handleNext} disabled={activeStep === 5}>
          Next
          {theme.direction === 'rtl' ? (
            <KeyboardArrowLeft />
          ) : (
            <KeyboardArrowRight />
          )}
        </Button>
      }
      backButton={
        <Button size="small" onClick={handleBack} disabled={activeStep === 0}>
          {theme.direction === 'rtl' ? (
            <KeyboardArrowRight />
          ) : (
            <KeyboardArrowLeft />
          )}
          Back
        </Button>
      }
    />
  );
}

The Progress Variant Mobile Stepper is a useful navigation tool, particularly in scenarios with a large number of steps or when steps are inserted dynamically during the process based on user interactions. It provides a clear indication of overall progress, enhancing the user experience.

MUI Progress Variant Mobile Stepper

Final Thoughts on Material UI Stepper Component

In conclusion, the Material UI Stepper component offers a powerful and flexible solution for creating step-by-step navigation in your React applications. With its various customization options and versatile variants, you can tailor your stepper to match the specific requirements of your project. Whether you need a simple linear stepper, a more complex non-linear stepper, or even a mobile-friendly stepper with different display options, Material UI’s Stepper component has you covered.

By following the examples and guidelines outlined in this article, you can easily implement a feature-rich stepper in your React application. The combination of Material UI’s components and React’s flexibility allows you to create intuitive and user-friendly interfaces that guide users through complex processes with ease.

Remember that the key to building an effective stepper is understanding your users’ needs and designing a seamless flow that enhances their experience. Material UI’s Stepper component, along with the power of React, empowers you to achieve just that. So, go ahead and implement your custom stepper, and take your React applications to the next level with structured and intuitive navigation. Happy coding!

Further Readings

If you enjoyed reading this piece, consider reading other articles from our blogs and also, my recommendations:

For your reference, you can also check out the below YouTube video to learn more about the Material UI stepper component.

Shadrach Abba

Shadrach Abba