ReactJS change background image dynamically?

53,679

Solution 1

You haven't specified when would you like to change backgroundImage, so I've created version which changes it with onClick:

React.createClass({
    getInitialState: function () {
        nextImg: false,
    },
    handleClick: function () {
        this.setState({ nextImg: !this.state.nextImg })
    },
    render: function() {
        var imgUrl = this.state.nextImg ? this.state.nextImgSrc : this.state.song.imgSrc;
        var divStyle = {
            backgroundImage: 'url(' + imgUrl + ')'
        }

        return (
            <li>
                <div ref="image-pane" style={divStyle} onClick={this.handleClick} className="player"></div>
            </li>
        )
    }
});

Notice that backgroundImage: 'url(' + imgUrl + ')' no longer must have trailing semicolon, in fact the trailing semicolon will cause React to raise and error.

Solution 2

This is caused by the trailing semicolon in your style. See react issues #2862.

Share:
53,679
rabishah
Author by

rabishah

I often experiment and learn from my Personal Projects where as in Professional Work, I try to learn by experience. Travelling, Music, Manga and Hacking daily life tools / activities.

Updated on July 09, 2022

Comments

  • rabishah
    rabishah almost 2 years

    I was trying to change background image style dynamically for the following div:

    Here is my component for changing it,

    render: function() {
      var divImage = {
        backgroundImage : "url(" + this.state.song.imgSrc + "),url(" + this.state.nextImgSrc + ");" 
      };
    
      return (
        <li>
          <div ref="image-pane" className="player" style={divImage}></div>
        </li>
      )
    }
    

    Thanks for the help

  • Harkirat Saluja
    Harkirat Saluja about 8 years
    why does semicolon cause an error in this? @daniula
  • daniula
    daniula about 8 years
    @HarkiratSaluja This was an issue with React itself. See github.com/facebook/react/issues/2862 pointed out by FakeRainBrigand