score:2

Accepted answer

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.

score:0

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

Related Query

More Query from same tag