Reputation: 137
I am trying to make a simple slideshow with fade in animation using react hooks. But my animation works only on first slide and not for others.
This is function code:
import React, { useEffect, useRef, useState } from "react";
import './Homepage.css';
const Homepage = () => {
const slides = [
"../../backgroundImages/1a.jpg",
"../../backgroundImages/1b.jpg",
"../../backgroundImages/1.jpg"
];
const playRef = useRef<any>(null);
const [slideIndex, setSlideIndex] = useState<number>(0);
useEffect(() => {
playRef.current = nextSlide;
});
useEffect(() => {
const play = setInterval(() => {
playRef.current();
}, 3000);
return () => {
clearInterval(play);
}
}, []);
const nextSlide = () => {
slideIndex >= slides.length -1
? setSlideIndex(0)
: setSlideIndex((slideIndex) => slideIndex + 1);
}
return(
<img alt='background' src={slides[slideIndex]}
className='homepage-background-div'
/>
);
}
export default Homepage;
and this is css:
.homepage-background-div {
position: absolute;
top: 0;
height: 100vh;
width: 100vw;
z-index: -1;
animation: fadein 2s;
}
@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
I have red answers for similar questions here on stackoverflow as well as many others articles and tutorials but was not able to solve the issue. Any help will be more than welcomed.
Upvotes: 0
Views: 193
Reputation: 332
add key={slides[slideIndex]}
to tag img
<img
alt="background"
key={slides[slideIndex]}
src={slides[slideIndex]}
className="homepage-background-div"
/>
Upvotes: 2