Update snippets
This commit is contained in:
@ -1,32 +1,35 @@
|
||||
---
|
||||
title: Carousel
|
||||
tags: components,children,state,effect,intermediate
|
||||
tags: components,children,state,effect,advanced
|
||||
---
|
||||
|
||||
Renders a carousel component.
|
||||
|
||||
- Use the `React.useState()` hook to create the `active` state variable and give it a value of `0` (index of the first item).
|
||||
- Use an object, `style`, to hold the styles for the individual components.
|
||||
- Use the `React.useEffect()` hook to update the value of `active` to the index of the next item, using `setTimeout`.
|
||||
- Destructure `props`, compute if visibility style should be set to `visible` or not for each carousel item while mapping over and applying the combined style to the carousel item component accordingly.
|
||||
- Render the carousel items using `React.cloneElement()` and pass down rest `props` along with the computed styles.
|
||||
- Use the `useState()` hook to create the `active` state variable and give it a value of `0` (index of the first item).
|
||||
- Use the `useEffect()` hook to update the value of `active` to the index of the next item, using `setTimeout`.
|
||||
- Compute the `className` for each carousel item while mapping over them and applying it accordingly.
|
||||
- Render the carousel items using `React.cloneElement()` and pass down `...rest` along with the computed `className`.
|
||||
|
||||
```css
|
||||
.carousel {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.carousel-item {
|
||||
position: absolute;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.carousel-item.visible {
|
||||
visibility: visible;
|
||||
}
|
||||
```
|
||||
|
||||
```jsx
|
||||
const Carousel = ({ carouselItems, ...rest }) => {
|
||||
const [active, setActive] = React.useState(0);
|
||||
let scrollInterval = null;
|
||||
const style = {
|
||||
carousel: {
|
||||
position: 'relative'
|
||||
},
|
||||
carouselItem: {
|
||||
position: 'absolute',
|
||||
visibility: 'hidden'
|
||||
},
|
||||
visible: {
|
||||
visibility: 'visible'
|
||||
}
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
scrollInterval = setTimeout(() => {
|
||||
setActive((active + 1) % carouselItems.length);
|
||||
@ -35,15 +38,12 @@ const Carousel = ({ carouselItems, ...rest }) => {
|
||||
});
|
||||
|
||||
return (
|
||||
<div style={style.carousel}>
|
||||
<div className="carousel">
|
||||
{carouselItems.map((item, index) => {
|
||||
const activeStyle = active === index ? style.visible : {};
|
||||
const activeClass = active === index ? ' visible' : '';
|
||||
return React.cloneElement(item, {
|
||||
...rest,
|
||||
style: {
|
||||
...style.carouselItem,
|
||||
...activeStyle
|
||||
}
|
||||
className: `carousel-item${activeClass}`
|
||||
});
|
||||
})}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user