Home > Software design >  Is there a way to loop through an array in React using useState?
Is there a way to loop through an array in React using useState?

Time:08-24

I have an array of images

image: [interiorDesignOne, interiorDesignTwo, interiorDesignThree],

and state like these

 const [imageIndex, setImageIndex] = useState(0);

I then access the correct image using the index in my JSX like these

   <img
      src={image[imageIndex]}
      alt="Project Image"
      className="project-image cursor"
    />

I want to create a sort of slide functionality that changes the image index every 5 seconds. My initial approach was to add 1 to the state each time but it gets to four then my HTML explodes.

Not working

 const changeShownImage = () => {
    setTimeout(() => {
      if (imageIndex === project.images.length) {
        setImageIndex((prev) => prev - 1);
      }
      setImageIndex((prev) => prev   1);
      changeShownImage();
    }, 5000);
  };

I want it in such away that if I reach the end of the array I go back to 0 (The beginning).

CodePudding user response:

Indexes start at zero. imageIndex === project.images.length - 1 should work.

CodePudding user response:

How about you add the length check within the setImageIndex function as well. Try something like this:

setImageIndex(prev => {
    return prev === project.images.length ? 0 : prev   1;
});

CodePudding user response:

You can use setInterval() instead of setTimeout()

 const changeShownImage = () => {
    setInterval(() => {
      setImageIndex(prev => prev === project.images.length ? 0 : prev   1;
      );
    }, 5000);
  };
  • Related