Home > Back-end >  How do I loop an image carousel with React setState and setInterval?
How do I loop an image carousel with React setState and setInterval?

Time:10-08

I am trying to set up an image carousel that loops through 3 images when you mouseover a div. I'm having trouble trying to figure out how to reset the loop after it reaches the third image. I need to reset the setInterval so it starts again and continuously loops through the images when you are hovering over the div. Then when you mouseout of the div, the loop needs to stop and reset to the initial state of 0. Here is the Code Sandbox:

Edit how-do-i-loop-an-image-carousel-with-react-setstate-and-setinterval

CodePudding user response:

Your setCount should use a condition to check to see if it should go back to the start:

setCount((prevCount) => prevCount === images.length - 1 ? 0 : prevCount   1);

This will do setCount(0) if we're on the last image—otherwise, it will do setCount(prevCount 1).

CodePudding user response:

Anything involving timers/intervals is an excellent candidate for Edit hungry-einstein-d8pe0

As to why your code didn't work, a few things:

  1. You meant to say if (count === 2) ..., not count === 3. Even better would be to use the length of the images array instead of hardcoding it
  2. Moreover, the value of count was stale inside of the closure, i.e. after you updated it using setCount, the old value of count was still captured inside of updateCount. This is actually the reason to use functional state updates, which you did when you said e.g. setCount((prevCount) => prevCount 1)
  3. You would have needed to loop the count inside the interval, not clear the interval on mouse over. If you think through the logic of it carefully, this should hopefully be obvious
  4. In general in react, using a function local variable like timer is not going to do what you expect. Always use state and effects, and in rarer cases (not this one), some of the other hooks like refs
  • Related