Home > Back-end >  How can I change slides with useState in react?
How can I change slides with useState in react?

Time:02-06

It's probably a basic stuff, but I'm trying to figure out how can I change slides clicking on button. I have divs with data from movies API, so I'm clicking a button and I change slides, toggling active class in it. I can imagine doing it in plain javascript, but I'm trying to understand how can I do it in React. The function looks like this:

 const [currentSlide, setCurrentSlide] = useState(0);
function changeSlide(){
      if(currentSlide <= few_movies.length){
          setCurrentSlide(currentSlide   1);
      }else if(currentSlide >= few_movies.length){

      }
  }

So here, if currentSlide is less than length of movies array, I set the currentSlide to the next one. But I'm trying to figure out what could I do if currentSlide reaches an endpoint. I tried doing setCurrentslide(0) so it starts from the first slide again, but it doesn't really make sense. Code for slide div:

<div className={`poster__item ${currentSlide===key ? 'active' : ''}`}</div>

CodePudding user response:

Quick answer YES you can make slides change using useState hook.

I suggest you hold all slides(movies) in an array or to have some indexed value for them like id, and then you can just make the math to change them based on the current slide index. and on click event should increment or decrement the index if the current slide is for example 5 and you want to see prev slide you should just set the value of the state to current - 1. And that is basically the logic.

For returning ( displaying the slide ) You just watch which data from API have the same id (index) as the current slide, and just display its data.

Hope you could understand and I did not confuse you. Good luck, happy codding.

CodePudding user response:

instead of setting it to setCurrentslide(0) why not just do nothing ?

same if they are at slide index 0 then don't let them go further down than 0

currentSlide.length >= few_movies.length ? console.log('do nothing') : setCurrentSlide(oldState => oldState  1)
  •  Tags:  
  • Related