How to use Material UI MobileStepper to make a carousel view with multiple item per view
Mui’s mobile stepper is great if we want to make a carousel view, but what if we want to show multiple item per view? It’s pretty simple too. In this article we will create a component <SwipeableMobileStepper />
which takes an array of elements we want to turn into a carousel view children: JSX.Element[]
, and itemsPerView
so we can render whatever number of items per view as we want.
Preview
How
We are going to start with this example in mui’s documentation, only a few lines of changes are needed to turn it into our generic carousel component.
TL;NR
Step 1
In our component SwipeableMobileStepper.tsx, pass in the props:
interface ISwipeableMobileStepperProps {
children: JSX.Element[]; // the items to turn into carousel
itemsPerView: number; // how many items we want in each view
}
Step 2
Calculate how many steps there should be(line 18):
const maxSteps = Math.ceil(children.length / itemsPerView);
Step 3
Render a container element for each step (line 39):
{[...Array(maxSteps)].map((_, index) => {
return (
<Box
key={`step-${index}`}
sx={{
display: "flex",
alignItems: "stretch",
justifyContent: "space-evenly",
}}
>
{...} // this is our next step
</Box>
);
})}
Step 4
Render {itemsPerView} items within each step container (line 49):
{children.slice(
index * itemsPerView,
index * itemsPerView + itemsPerView
)
.map((child, childIndex) => {
return (
<Box sx={{ mx: 1 }} key={`step-${index}-${childIndex}`}>
{React.cloneElement(child as JSX.Element, {})}
</Box>
);
})}
That’s it. There we have a generic component that we can pass in the elements we want to turn into a carousel view and how many elements we want to show per view. Enjoy coding =)