Reputation: 73
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
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
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
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