Kwhitejr
Kwhitejr

Reputation: 2306

How to rotate <img> source at interval in a React component?

Fairly straightforward issue, but my brain isn't clicking. In the very basic React component below, the source ought to transition and change at a set interval.

import React from 'react';

export default React.createClass({

  componentDidMount () {
    setInterval((function() {
      // switch the image source
    })(), 5000)
  }

  render () {

    const images = [
      "/assets/images/img01",
      "/assets/images/img02",
      "/assets/images/img03",
      "/assets/images/img04",
    ];

    return (
      <div id="rotatingImg">
        <img src="/assets/images/img01.jpg" />
      </div>
    )
  }
});

Upvotes: 0

Views: 2183

Answers (1)

Vitaly Kravtsov
Vitaly Kravtsov

Reputation: 970

You need something that will re-render your component from inside. Change state for this. Everytime state changes component re-renders.

import React from 'react';

export default React.createClass({

  constructor(props) {
    super(props);

    this.state = {
      currentImage: 0
    };
  }

  getRandomImageId() {
    const min = 0;
    const max = 3;
    return Math.floor(Math.random() * (max - min)) + min;
  }

  componentDidMount () {
    setInterval((function() {
      this.setState({
        currentImage: this.getRandomImageId()
      });
    })(), 5000)
  }

  render () {

    const images = [
      "/assets/images/img01",
      "/assets/images/img02",
      "/assets/images/img03",
      "/assets/images/img04",
    ];

    return (
      <div id="rotatingImg">
        <img src={images[this.state.currentImage]} />
      </div>
    )
  }
});

Upvotes: 2

Related Questions