Rajdeep Ratan
Rajdeep Ratan

Reputation: 73

How to use if else condition inside react object

Can anyone tell me an alternative to use if.. else.. condition inside a react object

const background = {
    color: {
      if ( this.props.status == 'broker') {
        background : '#FFFFFF'
      } esle {
        background : 'green'
      }
    }
}

Upvotes: 0

Views: 949

Answers (3)

sbriscoe13
sbriscoe13

Reputation: 1

Answer by M0meni helped me-- but I still got an error of "objects not valid as react child". So i changed the solution a little bit and got it to work. Instead of return { background: '#fff' } I used return { '#fff' }

Upvotes: 0

m0meni
m0meni

Reputation: 16435

You don't need to evaluate it all inline. Nested ternary statements can get pretty ugly. You can just make a function and pass that result in:

function bgColor(status) {
  if (status === 'broker') {
    return { background: '#fff' }
  }

  if (status === 'whatever' {
    // return ...
  }

  // whatever else
}

const background = {
  color: bgColor(this.props.status)
}

Upvotes: 0

Josh Beam
Josh Beam

Reputation: 19772

You could use a ternary:

const background = {
    color: this.props.status === 'broker' ? '#ffffff' : 'green'
}

This could get limiting and/or hard to read if you want more conditions, so you could also make it function, but you'll just have to be careful of how/where you invoke it:

const background = {
    color: function() {
      let color

      if(this.props.status === 'broker') {
        color = '#ffffff'
      } else {
        color = 'green'
      }

      return color
    }
}

Upvotes: 1

Related Questions