multiple condition in ternary operator in jsx
To chain ternary operations you need to add another ternary operator to be returned when the conditions are not met, for example:
a === true ? a : b
In place of b
you would add a new ternary operator, like so:
a === true ? a : b === true ? b : c
Bonus:
When you're just checking for null/undefined/false you can use the pipe operator, for example this:
var x = a !== null ? a : b;
Can be simplified to:
var x = a || b;
And pipe operators can be chained infinitely like ternary operators.
Multiple condition in ternary operator in JSX
and JS
style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'cancel' ? 'red' : 'green'}}
I would suggest using functions if your conditions get complicated, to not degrade your code readability.
getBackgroundColor(status) {
if (status === 'approved') {
return 'blue';
}
if (status === 'pending') {
return 'red';
}
return 'black';
}
render() {
// ...
return (
<div style={{ 'backgroundColor': this.getBackgroundColor(status) }}></div>
);
}
You could do the following:
<div style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'pending' ? 'black' : 'red'}}>
</div>
This means if status === 'approved'
set the background color as blue, if status === 'pending'
set it as black, else set it as red.