Ternary operators in JSX
As you can see, we use two ternary operators to conditionally style a container in React.
A quick recap: ternary operators are composed of a condition, an expression if the condition is true, and an expression if it’s false. Syntax looks like this:
darkMode ? "black" : null
The condition is followed by a question mark, which is followed by an expression to run if the condition is true.
In the example above, ternary operator in JSX evaluates darkMode. If the condition is true, it will return ‘black’. If it’s false, it will return null.
darkMode is a state variable that contains a Boolean value. Clicking the ‘light switch’ button resets current darkMode value.
Ternary operators outside JSX
Nested ternary operators in React
Sometimes a simple ‘evaluate condition, return X if true, Y if false’ isn’t enough. You may need to chain multiple conditions together.
Let’s look at an example:
const value = 2 + 2 == 4 ? "text" : darkMode ? "dark" : null;
First, ternary operator checks first condition 2+2 == 4. If it’s true, it returns ‘text’. If not, we return another ternary operator that checks darkMode variable.
You still need curly braces to embed it in JSX.