3

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

1
  • Hi Justin, I just provided you a solution below, that should give you enough insight on how to integrate this feature. Let me know if you have any questions, and please consider upvoting and marking it as the answer :) Commented Jul 19, 2019 at 18:07

2 Answers 2

6

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.
Sign up to request clarification or add additional context in comments.

Comments

0

The main issue with your code is that you called init function with in render function, whenever state get update render executes as well, so init function call again and again each time render function execute

the solution is to set intervals in componentDidMount function

componentDidMount run only one time after component mount in the DOM, for help related to react life cycle function do visit the official documentation

https://reactjs.org/docs/react-component.html

also have a look this post image

https://reactjs.org/docs/react-component.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.