Search code examples
javascriptreactjsternary

Ternary operator issue in React's componentDidMount()


I have an issue with the ternary operator in my component. I've created a function to check if Sun's up and return boolean:

dayTime() {
  const time = new Date();
  const sunrise = new Date(this.state.sunrise*1000);
  const sunset = new Date(this.state.sunset*1000);
  return time > sunrise && time < sunset;
}

I than used ternary operator to call the function and set backgroundImage depending on boolean:

componentDidMount() {
  document.body.style.backgroundImage = "url(" + (this.dayTime()? day_img_cov : night_img_cov) + ")";
    }

Unfortunately, the ternary won't work properly. It picks the second image all the time. Yet when I use the ternary inside of render(), it works correctly:

render() {

  return (
    <div className="app" style={{backgroundImage: "url(" + (this.dayTime()? day_img : night_img) + ")"}}>
      ...
    </div>
}

Solution

  • You haven't shown your full class so I don't know where this.state.sunrise and this.state.sunset is coming from, but I'm betting they're not set properly when you call this.dayTime() in componentDidMount.

    Either initialize them properly in your constructor or make sure you update the background of body whenever they are modified.

    The best way of doing it is your second, working, example since that's automatically run whenever the state changes - it also doesn't modify the DOM outside of the React tree, which is good practice.