Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing an Image on in time interval using react

I am trying to change the image displayed every 1 second the first image appears then switches to the alt display and does not continue switching the pictures

export default class Slideshow extends Component {

    constructor(props) {
        super(props);
        this.getImageId = this.getImageId.bind(this);
        this.switchImage = this.switchImage.bind(this);
        this.init = this.init.bind(this);
        this.state = {
            currentImage: 0,
            image: 0

        };
    }

    getImageId() {
        if(this.currentImage < 3) {
            this.setState({
                currentImage: this.state.currentImage +1
            })
        } else {
            this.setState({
                currentImage: 0
            })
        }
        return this.currentImage;
    }

    switchImage() {
            this.setState({
                image: this.getImageId()
            });
    }

    init() {
        setInterval(this.switchImage, 1000)
    }


    render() {
        const imagePath = [guy, girl, wash, swifer];
        this.init();

        return (
            <div className="slideshow-container">
                <img src={imagePath[this.state.image]} alt="cleaning images"/>      
            </div>
        );
    }
}

Pictures will switch every 1 seconds to the next picture in the array and go back to original after going through whole array

like image 710
Justin Alia Avatar asked Feb 05 '26 15:02

Justin Alia


1 Answers

Try something like this instead: https://codesandbox.io/s/naughty-sara-q3m16

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.switchImage = this.switchImage.bind(this);
    this.state = {
      currentImage: 0,
      images: [
        "https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
        "https://img.purch.com/w/660/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNC84MzAvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzExMTA1NzIxNTkuanBn",
        "https://d17fnq9dkz9hgj.cloudfront.net/uploads/2012/11/152964589-welcome-home-new-cat-632x475.jpg",
        "https://i.ytimg.com/vi/jpsGLsaZKS0/maxresdefault.jpg"
      ]
    };
  }

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

  componentDidMount() {
    setInterval(this.switchImage, 1000);
  }

  render() {
    return (
      <div className="slideshow-container">
        <img
          src={this.state.images[this.state.currentImage]}
          alt="cleaning images"
        />
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

We can simplify your code by doing a couple of things:

  1. Put the images-array in the state, so that we can iterate over the image-paths and keep track of the current images index.
  2. So now we can consolidate switchImage and getImageId into a single function that serves the same purpose. We just check the currentImage (index) against the length of the array.
  3. React also has a life-cycle method called componentDidMount() which executes logic right after a component is rendered the first-time. I used this to replace the init() function. There is an issue with calling init() in render(). Every time a component re-renders, it executes the logic in render(), which means you would be creating a new setInterval() on every subsequent re-render. componentDidMount() only triggers a single time, making it perfect for defining intervals.
like image 167
Chris Ngo Avatar answered Feb 07 '26 03:02

Chris Ngo