Im trying to change my image every second in react inside of a map. However this doesnt seem to be working. Here is my code:
function ImageGrid() {
const {shell, gridImage} = styles
const squishAnimals = [
'/SquishAnimalDemo(1).png',
'/SquishAnimalDemo(2).png',
'/SquishAnimalDemo(3).png',
'/SquishAnimalDemo(4).png',
'/SquishAnimalDemo(5).png',
'/SquishAnimalDemo(6).png',
'/SquishAnimalDemo(7).png',
'/SquishAnimalDemo(8).png',
'/SquishAnimalDemo(9).png'
];
const [images, setImages] = useState(squishAnimals);
const [currentImage, setCurrentImage] = useState(0);
function changeBackgroundImage() {
let newCurrentImg = 0;
const noOfImages = images.length;
if (currentImage !== noOfImages - 1) {
newCurrentImg += currentImage;
}
setCurrentImage(newCurrentImg);
}
useEffect(() => {
const interval = setInterval(() => changeBackgroundImage(), 1000);
if (interval) {
clearInterval(interval);
}
});
return (
<div className={shell}>
{squishAnimals.map((image, index) => {
return (
index === 4 ?
<img className={gridImage} src={images[currentImage]} alt={`${index}-${image}`}/> :
<img className={gridImage} src={image} alt={`${index}-${image}`}/>
)
})}
</div>
);
}
Any help as to why it may not be working would be great. Thanks 🙂