''Setinterval' for slide show function is not working properly in React
I am trying to build a simple image slide show here but images are not changing as I am expecting.
const [bannerbg, setbannerbg] = useState({
backgroundImage:
"url('https://images.pexels.com/photos/1864640/pexels-photo-1864640.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940')",
});
const [img2, setimg2] = useState({
backgroundImage:
"url('https://images.pexels.com/photos/1864653/pexels-photo-1864653.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1')",
});
const [img3, setimg3] = useState({
backgroundImage: "url('https://cdn.wallpapersafari.com/15/98/I0tmB4.jpg')",
});
let i = 0;
const sliderImages = [bannerbg, img2, img3];
function backBannerChange() {
if (i < sliderImages.length - 1) {
i++;
} else {
i = 0;
}
setbannerbg(sliderImages[i]);
}
setInterval(backBannerChange,3000);
Html:-
<div className="disc-wrapper" style={bannerbg}></div>
First image is changing to second one but second image is not changing to third one.
Solution 1:[1]
your function must set in lifecycle of component:
please use useeffect for this:
useEffect(() => {
setInterval(backBannerChange,3000);
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | foad abdollahi |
