Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
How can I change slides with useState in react?

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>

Edit: So I added useInterval so it'd loop automatically through movives, but now it only changes back and forth between two first items without going further. Code looks like this:

useEffect(() =>{
        setInterval(() =>{
          if(currentSlide < few_movies.length - 1){
            setCurrentSlide(currentSlide + 1);
        }else(currentSlide >= few_movies.length){
          setCurrentSlide(0);
        }
        }, 2000)
  },[])
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The updated code you posted, with the setInterval inside the useEffect id problematic because the currentSlide will never change inside it, since the useEffect has no dependencies. It will always remain at 0, the initial value.

You can use setTimeout instead (with the use of the dependency list of useEffect), or you can use the function form which provides the current value and you return the new one.

so either

useEffect(() => {
  const timeout = setTimeout(() => {
    if (currentSlide < few_movies.length - 1) {
      setCurrentSlide(currentSlide + 1);
    } else {
      setCurrentSlide(0);
    }

    return () => clearTimeout(timeout);
  }, 2000);
}, [currentSlide])

or

useEffect(() => {
  const interval = setInterval(() => {
    setCurrentSlide((currentSlideValue) => {
      if (currentSlide < few_movies.length - 1) {
        return currentSlide + 1;
      }
      return 0;
    })

    return () => clearInterval(interval);
  }, 2000);
}, [])

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda