/
slider.jsx
73 lines (71 loc) · 2.13 KB
/
slider.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import {useState, useEffect} from 'react';
import InputComp from './comp/inputComp';
import './styl.css';
const Slider = () => {
const sliderList = [
{
id: 0,
img: 'https://source.unsplash.com/random/1920x1080'
},
{
id: 1,
img: 'https://source.unsplash.com/random/1920x1081'
},
{
id: 2,
img: 'https://source.unsplash.com/random/1920x1082'
},
{
id: 3,
img: 'https://source.unsplash.com/random/1920x1083'
},
{
id: 4,
img: 'https://source.unsplash.com/random/1920x1084'
}
]
const [slideId,setSlideId] = useState(0);
const initialArray = [true, false, false, false, false];
const [isAnimating, setIsAnimating] = useState(initialArray);
useEffect(() => {
const timer = setTimeout(() => {
setSlideId((slideId + 1) % initialArray.length); // the value is divided by the length of the array, after reaching the last index the function returned to the first argument
setIsAnimating(prevState =>
prevState.map((user, i) => i === slideId ? true : false)
);
}, 20000); // here you can change slide display time 20000 = 20s
return () => clearTimeout(timer);
}, [slideId]);
//function that change slide on click
const handleButtonClick = index => {
setSlideId(index);
setIsAnimating(prevState =>
prevState.map((user, i) => i === index ? true : false)
);
};
return (
<>
// this is slider
<div
className="slider"
style={{backgroundImage: `url(${sliderList[slideId].img})`}}
>
</div>
// if you don't want buttons to change the slide, skip this component
<div className="slider-menu">
<div className="slider-indic-bar">
{sliderList.map((user, i) =>{
return <InputComp
key={sliderList[i].id}
slideId={i}
anim={isAnimating[i]}
handleButtonClick={handleButtonClick}
/>
})
}
</div>
</div>
</>
);
};
export default Slider;