gorniczy
gorniczy

Reputation: 77

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>
}

Upvotes: 1

Views: 643

Answers (2)

gazdagergo
gazdagergo

Reputation: 6711

Use isDaytime as a state and manipulate the classes based on that. The dayTime function can even be private outside of class (if it not uses state variables).

js

import classnames from 'classnames'

class Wallpaper extends Component {
  state = {
    isDaytime: daytime();
  }

  render() {
    const { isDaytime } = this.state;
    return (
      <div className={classnames('bg', {
        bg__daytime: isDaytime 
        bg__sunset: !isDaytime
      })} />
    )
  }
}

css

.bg {
  ...
}

.bg__daytime {
  background-image: url(day_img.png);
}

.bg__sunset {
  background-image: url(night_img.png);
}

Upvotes: 0

Raniz
Raniz

Reputation: 11113

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.

Upvotes: 2

Related Questions