Material UI is a Material Design library made for React.
It’s a set of React components that have Material Design styles.
In this article, we’ll look at how to customize steppers with Material UI.
We can add non-linear steppers to add a stepper that allows users to navigate to any step they want.
For example, we can write:
import React from "react";
import Stepper from "@material-ui/core/Stepper";
import Step from "@material-ui/core/Step";
import StepButton from "@material-ui/core/StepButton";
import Button from "@material-ui/core/Button";
function getSteps() {
return ["step 1", "step 2", "step 3"];
}
function getStepContent(step) {
switch (step) {
case 0:
return "do step 1";
case 1:
return "do step 2";
case 2:
return "do step 3";
default:
return "unknown step";
}
}
export default function App() {
const [activeStep, setActiveStep] = React.useState(0);
const [completed, setCompleted] = React.useState({});
const steps = getSteps();
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()
? 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 (
<div>
<Stepper nonLinear activeStep={activeStep}>
{steps.map((label, index) => (
<Step key={label}>
<StepButton
onClick={handleStep(index)}
completed={completed[index]}
>
{label}
</StepButton>
</Step>
))}
</Stepper>
<div>
{allStepsCompleted() ? (
<div>
All steps completed - you're finished
<Button onClick={handleReset}>Reset</Button>
</div>
) : (
<div>
{getStepContent(activeStep)}
<div>
<Button disabled={activeStep === 0} onClick={handleBack}>
Back
</Button>
<Button variant="contained" color="primary" onClick={handleNext}>
Next
</Button>
{activeStep !== steps.length &&
(completed[activeStep] ? (
`Step {activeStep + 1} already completed`
) : (
<Button
variant="contained"
color="primary"
onClick={handleComplete}
>
{completedSteps() === totalSteps() - 1
? "Finish"
: "Complete Step"}
</Button>
))}
</div>
</div>
)}
</div>
</div>
);
}
#programming #software-development #javascript #web-development #technology