Al_Milligan
Al_Milligan

Reputation: 119

Changing background color depending on state in react.js

I am working on a simple app, background color should be different depending on season. So far I've written:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
        backgroundColor: 'blue'
    }
  }

    handleSeason = (time) => {
    const months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ]
    const month = months[time.getMonth()];

    if (month === 'January' || month === 'February' || month === 'December') {
      this.setState({backgroundColor: 'white'});
    } else if
      (month === 'March' || "April" || 'May') {
      this.setState({ backgroundColor: 'yellow' });
    } else if 
    (month==='June' || month ==='July' ||month ==='August'){
      this.setState({ backgroundColor: 'green' });
     } else {
      this.setState({ backgroundColor: 'red' });
    }
  }

  

in the render, I return the following div:

      <div className='app' style={{backgroundColor: this.state.backgroundColor }}>

The background stays blue. I am not sure where is the issue. The console shows no errors. Any tips will be appreciated.

Upvotes: 0

Views: 976

Answers (2)

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16334

You have two things to fix in the code

The second if block is like this

(month === 'March' || "April" || 'May') {

This will always set the state to yellow as the strings April and May would be treated as true, so change it like below

   else if (month === "March" ||month ===  "April" ||month ===  "May") {

Also check whether you are calling the the handleSeason function like below

this.handleSeason(new Date());

Upvotes: 1

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

I see nothing that would trigger the handleSeason function...

Maybe it would be nice to try :

componentDidMount() {
  this.handleSeason(new Date())
}

Upvotes: 1

Related Questions