Ternary operator is a JavaScript feature commonly used for building apps in React. In this article, you will learn about ternary operators, their use cases and usefulness for implementing dynamic features in React.

Ternary operators in JSX

React components are a combination of JavaScript and JSX. Ternary operators are uniquely useful because you can use them in JavaScript as well as JSX.

To embed JavaScript expressions (like ternary operators) in JSX, you need to wrap them with curly braces. Let’s look at an example where we use a ternary operator 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

React functional components are written in plain JavaScript. Ternary operator is a JavaScript feature, so you can use it as normal.

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.

Writing a nested ternary operator is simple. First, you need a condition. If it’s evaluated as true, you can specify a JavaScript expression. If it’s false, you can return another ternary operator with a new condition.

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.