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

203
Visualizações
Changing background image setinterval only calling once

This is in REACT.JS. I have combed through the different posts on here trying to find a solution, however I have not been able to get this to run more than once. Any ideas would be greatly appreciated! I have the component code below

import React, { Component } from 'react'
import './Login.css'
import LoginHousing from './LoginHousing'
import bg1 from '../../images/backgrounds/lawn-maintenance.jpg'
import bg2 from '../../images/backgrounds/body-shop.jpg'
import bg3 from '../../images/backgrounds/mechanic.jpg'
import bg4 from '../../images/backgrounds/painting.jpg'
import bg5 from '../../images/backgrounds/hair-stylist.jpg'

export default class Login extends Component {
constructor(){
    super()
    this.state = {loginBg: bg1}
}

// Background slideshow effect on mount, changing every 2 seconds
changingBackground() {
    let i = 0
    const images = [bg1, bg2, bg3, bg4, bg5]

    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }

    this.setState({loginBg: images[i]})
}


componentDidMount() {
    this.timer = setInterval(
        () => this.changingBackground(),
        2000
    );
}

componentWillUnmount(){
    clearInterval(this.timer)
}

render() {
    return (
        <div className='login vw-100 vh-100' style={{backgroundImage: `url(${this.state.loginBg})`}}>
            <LoginHousing />
        </div>
    )
}
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

let i = 0

This variable is local to the function, so each time that function is executed in the interval, you basically start from the beginning.


You could change code to this:

changingBackground() {       
    this.setState((ps) => {
      return {
        index: (ps.index + 1) % this.images.length, // store images in instance field
      };
    });
  }

And then render:

this.images[this.state.index]

PS and constructor:

constructor() {
    super();
    this.state = { index: 0 };
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I will give you a little explanation before the solution for this, because when you are calling the this.changingBackground() it will always get to zero again, as you see in the first declaration of the let i = 0 so each time that function runs it will be zero, I think the best solution for this is making the counter for the background-images a state variable:

import React, { Component } from 'react';

export default class Login extends Component {
  constructor(){
      super();
      this.state = {loginBg: bg1, indexImage: 0}
  }

  changingBackground() {
      const images = [bg1, bg2, bg3, bg4, bg5]

      if (indexImage < images.length - 1) {
          this.setState({indexImage: this.state.indexImage + 1});
      } else {
          this.setState({indexImage: 0});
      }

      this.setState({loginBg: images[this.state.indexImage]});
  }


  componentDidMount() {
      this.timer = setInterval(
          () => this.changingBackground(),
          2000
      );
  }

  componentWillUnmount(){
      clearInterval(this.timer);
  }
}
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