Introduction
In this lab, we will explore how to create a carousel component using React. A carousel is a popular UI element that allows users to cycle through a set of images or content. By using the useState() and useEffect() hooks, we can build a simple yet functional carousel that automatically scrolls through a set of items.
Carousel
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
This code renders a carousel component. Here are the steps it takes:
- It uses the
useState()hook to create theactivestate variable and initializes it to0(the index of the first item in the carousel). - It uses the
useEffect()hook to set up a timer withsetTimeout(). When the timer fires, it updates the value ofactiveto the index of the next item in the carousel (using the modulo operator to wrap around to the beginning if necessary). It also cleans up the timer when the component unmounts. - It computes the
classNamefor each carousel item by mapping over them and applying the appropriate class based on whether the item is currently active or not. - It renders the carousel items using
React.cloneElement(), passing down any additional props using...rest, and adding the computedclassNameto each item.
The CSS styles define the layout of the carousel and its items. The carousel container has position: relative, while the items have position: absolute and visibility: hidden by default. When an item is active, it gets a visible class, which sets its visibility to visible.
.carousel {
position: relative;
}
.carousel-item {
position: absolute;
visibility: hidden;
}
.carousel-item.visible {
visibility: visible;
}
Here's the full code:
const Carousel = ({ carouselItems, ...rest }) => {
const [active, setActive] = React.useState(0);
let scrollInterval = null;
React.useEffect(() => {
scrollInterval = setTimeout(() => {
setActive((active + 1) % carouselItems.length);
}, 2000);
return () => clearTimeout(scrollInterval);
});
return (
<div className="carousel">
{carouselItems.map((item, index) => {
const activeClass = active === index ? " visible" : "";
return React.cloneElement(item, {
...rest,
className: `carousel-item${activeClass}`
});
})}
</div>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(
<Carousel
carouselItems={[
<div>carousel item 1</div>,
<div>carousel item 2</div>,
<div>carousel item 3</div>
]}
/>
);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the Carousel lab. You can practice more labs in LabEx to improve your skills.