Search code examples
cssreactjsbackground-image

Random background image with React


I'm actually working on a React app and currently trying to display a random background image. My idea was to import the 4 pictures, put them in an array and select randomly one item of the array :

import skyPicture1 from '../assets/pictures/sky.jpg'
import skyPicture2 from '../assets/pictures/sky2.jpg'
import skyPicture3 from '../assets/pictures/sky3.jpg'
import skyPicture4 from '../assets/pictures/sky4.png'


class HomeForUnlogged extends Component {


  constructor(props) {
    super(props)

    this.state = {
      bgStyle : {
        height: "100%",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
      }
    }
  }


  componentWillMount() {

    const pictureArray = [{skyPicture1}, {skyPicture2}, {skyPicture3}, {skyPicture4}];
    const randomIndex = Math.floor(Math.random() * pictureArray.length);
    const selectedPicture = pictureArray[randomIndex];

    this.setState({
      bgStyle: {
        backgroundImage: `url(${selectedPicture})`,
        height: "100%",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
      }
    })

  }


  render() {

    return (
      < div style={this.state.bgStyle} className="bg">
        <div className="row" >
          <div className="col-sm-4" style={{ marginTop: "30px", padding: "30px" }} > <TextHome /></div>
          <div className="col-sm-4" style={{ marginTop: "90px", padding: "30px" }}> <Login history={this.props.history} /></div>
          <div className="col-sm-4"> </div>
        </div>
      </div>
    );
  }
}

export default HomeForUnlogged;

But no picture is displayed at all. Does anyone have an idea, what I did wrong? I have no clue.


Solution

  • You make it as object, could you change it to const pictureArray = [skyPicture1, skyPicture2, skyPicture3, skyPicture4];