Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

react
communitycreator
ternary
conditional

How to use the ternary operator in React

Abel Lifaefi Mbula

Overview

The ternary operator, also called the conditional operator, is an alternative to the if...else statement. This operator has three parameters:

  • A condition followed by ? (question mark)
  • The expression to execute if the condition is true
  • The expression to execute if the condition is false

The syntax looks like this:

condition ? exprIfTrue : exprIfFalse
Syntax

Since React is a JavaScript (JS) library, we can use plain JS in React. However, React also uses JSX (a mix of JS and HTML). Because of this, we follow the following steps to do conditional rendering using the ternary operator in React.

Code

Let's create a list component such that it will show the list of users if there are any present, and return "No user available" if there aren't any.

This is the list of users that we will be using:

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

Now, let's show the list in React.

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

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

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

Explanation

  • Line 5: We define the list to be rendered in a variable called users.
  • Line 13: We set the condition showList to true to show the list. To see what happens if we set it to false, simply change the condition to false.
  • Lines 18 to 28: We see the conditional rendering in action.

RELATED TAGS

react
communitycreator
ternary
conditional
RELATED COURSES

View all Courses

Keep Exploring