The ternary operator, also called the conditional operator, is an alternative to the if...else
statement. This operator has three parameters:
?
(question mark)The syntax looks like this:
condition ? exprIfTrue : exprIfFalse
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.
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' }, ]
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') );
users
.showList
to true
to show the list. To see what happens if we set it to false, simply change the condition to false
.RELATED TAGS
CONTRIBUTOR
View all Courses