I want to change images every 2 seconds automatically with fade in animation, but my problem is when the next image is shown, the previous image disappears before the next image is displayed, so with the code that I have each image disappears completely showing the background of the page before showing the next one.
My goal is to keep the previous image a short time before the next one appears to avoid showing the background of the page.
function hero() {
const images = [
'/public/Hero-image-1.jpg',
'/public/Hero-image-2.jpg',
'/public/Hero-image-3.jpg'
];
const [currentIndexImage, setcurrentIndexImage] = React.useState(0);
const [fade, setFade] = React.useState(false);
React.useEffect(() => {
const interval = setInterval(() => {
setFade(false);
setTimeout(() => {
setcurrentIndexImage((prevIndex) => (prevIndex + 1) % images.length);
setFade(true);
}, 1000);
}, 2000);
// Cleanup the interval on component unmount
return () => clearInterval(interval);
}, []);
return (
<>
<div className="hero-img-container">
<div className="hero-imgs">
<img src={images[currentIndexImage]} className={fade ? 'fade' : 'fade-out'}/>
</div>
</>
.fade {
opacity: 1;
transition: opacity 0.5s ease-in-out;
}
.fade-out {
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
3
Answers
I got it where you are facing problem . so think of it like that suppose one image is disappearing other should start appearing same time.
so why not we positon another image just above it and then one starts fading out at the same time other starts fading in.
to achieve this we have to keep track of next image using states.
i have provided the code below i hope it will help.
I faced the same problem and and came by the following solution which was using
backgroundImage
in adiv
instead of usingimg
tag.I understand your issue. One solution is to position another image above the disappearing image and gradually fade out the first image while simultaneously fading in the second image. This can be achieved by keeping track of the next image using states. Below is the code that can help you implement this.