How to use the ternary operator in React

Key takeaways:

  • The ternary operator is a concise alternative to the if...else statement in JavaScript, widely used in React for conditional rendering.

  • The ternary operator has three parts: a condition, the expression to execute if the condition is true (after ?), and the expression to execute if the condition is false (after :).

  • The ternary operator seamlessly integrates with JSX, enabling dynamic and efficient rendering of different elements based on conditions.

  • The ternary operator provides a concise way to handle dynamic content rendering in React, improving code clarity and reducing verbosity compared to traditional conditionals.

  • When using the ternary operator in lists, include key props to ensure efficient rendering and avoid React warnings.

The ternary operator in React, often referred to as the conditional operator, is a powerful tool in JavaScript for making quick decisions based on conditions. It serves as a concise alternative to the traditional if...else statement. The operator is particularly useful in React conditional rendering, allowing you to display different elements based on certain conditions without cluttering your code.

Components of a ternary operator

The ternary operator has three main components:

  1. A condition followed by ? (question mark): This is the expression that evaluates to true or false.

  2. The expression to execute if the condition is true: This follows the ? and defines what will be displayed if the condition evaluates to true.

  3. The expression to execute if the condition is false: This follows the colon (:) and defines what will be displayed if the condition evaluates to false.

Syntax of a ternary operator

The syntax looks like this:

condition ? exprIfTrue : exprIfFalse
Syntax

Since React is built on JavaScript, we can seamlessly integrate plain JavaScript features, including the ternary operator syntax. However, React also utilizes JSX (JavaScript XML), a syntax extension that allows you to write HTML-like code within JavaScript. This unique combination enables us to achieve powerful conditional rendering in React with minimal code.

Implementing conditional rendering with the ternary operator

Let’s create a practical example to illustrate how the ternary operator can be used in JSX for conditional rendering. We’ll build a simple list component that displays a list of users if any are present; otherwise, it will show a message “No user available,” indicating that no users are available.

Sample user data

First, let’s define a list of users that we will use in our component:

const users = [
{ name: 'Sarah Lifaefi' },
{ name: 'Patience Kavira' },
{ name: 'Abel Lifaefi' },
{ name: 'Neema Kelekele' },
]
List of users

React component code

Now, let’s implement this logic in a React component.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);
Conditional rendering

Code explanation

In the above app.js code:

  • Line 5: We define a constant users that contains an array of user objects. Each object has a name property representing a user’s name that will be displayed in the list.

  • Line 13: We set the condition showList to true to indicate that we want to display the list of users. To see the alternative rendering, simply change the condition to false.

  • Lines 18–28: We use the ternary operator to conditionally render content within the return statement. If showList is true, we render the user list. If it’s false, we display the message “No user available,” indicating that no users are available.

    • Line 20: We start rendering a <div> that contains a header (<h1>) to label the user list as “Available users.”

    • Lines 21–24: We map over the users array to create a list of user names. Each user’s name is rendered inside a list item (<li>), with a unique key prop assigned using the user’s name for efficient rendering.

    • Line 28: In the else part of the ternary operator, we render a paragraph (<p>) stating, “No user available.” This will be displayed if showList is false.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

What is the main benefit of using the ternary operator in React for conditional rendering?

A)

It allows you to write HTML inside JavaScript.

B)

It replaces all JavaScript functions with simpler syntax.

C)

It provides a concise way to render different content based on conditions.

D)

It automatically optimizes React components for better performance.

Question 1 of 30 attempted

Conclusion

The ternary operator offers a concise way to handle conditional rendering in React, enabling dynamic UIs that respond to varying states. Ensure efficient performance by using unique key props in lists and maintaining clarity when nesting or implementing complex conditions.

This guide is great for beginners, covering key React concepts like rendering techniques. To further advance your skills, check out our blog, "The best React developer roadmap for 2024," for in-depth insights into the latest React tools and best practices.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to use the ternary operator for multiple conditions in React JS

To use a ternary operator for multiple conditions in React JS, you can nest the ternary operators. Each nested ternary operator handles a different condition, allowing you to render different elements based on each case. However, it’s crucial to ensure readability by keeping nested conditions simple or consider refactoring to if...else statements or functions if they become too complex.


Is the ternary operator faster than if...else statements?

The ternary operator is not inherently faster than if...else statements; both compile to similar machine-level code and perform similarly in terms of speed. The primary advantage of the ternary operator is its conciseness, which can make code easier to read and write when handling straightforward conditional rendering, especially in JSX.


What is the disadvantage of using a ternary operator?

The main disadvantage of using a ternary operator is that it can reduce code readability when overused or when handling complex conditions. Nested or long ternary operators can make the code difficult to understand and maintain, leading to potential errors during future updates. In such cases, using if...else statements or breaking logic into smaller functions is often more readable.


What does () => {} mean in React?

In React (and JavaScript in general), () => {} represents an arrow function. It is a concise syntax for writing functions. Arrow functions do not have their own this context, which makes them especially useful in React for defining inline functions, such as event handlers, without worrying about binding this.

Example in React:

<button onClick={() => console.log('Button clicked!')}>Click Me</button>

Here, () => console.log('Button clicked!') defines an inline arrow function that logs a message when the button is clicked.


Can I use ternary operator for 3 conditions?

Yes, you can use a ternary operator for 3 or more conditions by nesting ternary expressions. However, this can make the code harder to read, so it’s better to use nested ternary operators only when the logic is simple.

Example:

const result = score > 90 
  ? 'Excellent' 
  : score > 75 
    ? 'Good' 
    : 'Needs Improvement';

Here, the ternary operator evaluates three conditions:

  • If score > 90, it returns 'Excellent'.
  • If not, it checks if score > 75 and returns 'Good'.
  • Otherwise, it returns 'Needs Improvement'. For complex logic, consider using if...else statements for better readability.

What is the ternary?

The term “ternary” refers to anything involving three parts or elements. In programming, it specifically means an operator or construct that works with three operands. The word itself comes from the Latin root “ternarius,” meaning “consisting of three.”

In the context of programming:

  1. Ternary in general: It represents something with three components or values.

    Example: A system with three states or options could be described as “ternary.”

  2. Ternary operator: In many programming languages, this refers to the conditional operator (? :), which operates on three parts:

    • A condition
    • A result if the condition is true
    • A result if the condition is false

    Example:

    condition ? valueIfTrue : valueIfFalse;
    

Outside programming, “ternary” could describe anything involving three elements, like a ternary relationship in mathematics or a ternary phase diagram in chemistry. It simply means "three-part” in any context.


Free Resources