Bootcamp
Search…
7.1.1: Conditional Rendering

Learning Outcomes

  • To understand what conditional rendering means in JSX.
  • To be able to output different values to a page based on an If/Else condition.
  • To be able use the Javascript Ternary operator in the conditional output.

Introduction

JSX makes it easier to render specific HTML elements depending on program logic, using standard JS conditionals and logical syntax.

Conditional Variable Values

myEl is a JSX element that uses values of message and myRandomNum. The construction of the JSX element does not change, but the value of message depends on the value of myRandomNum.
src/index.jsx
1
import React from 'react';
2
import { render } from 'react-dom';
3
​
4
const myRandomNum = Math.random() * 10;
5
​
6
// Value of message depends on value of myRandomNum
7
let message;
8
if (myRandomNum > 5) {
9
message = <p>Wow past 5!!</p>;
10
} else {
11
message = <p>Not that big of a num :(</p>;
12
}
13
​
14
// Create a JSX element using myRandomNum and message
15
const myEl = (
16
<div>
17
<h1 className="hero-text">
18
Hey <span className="warning">Wow!</span>
19
</h1>
20
<p>Random Value: {myRandomNum}</p>
21
<div>{message}</div>
22
</div>
23
);
24
// Verify the element is what we expect
25
console.log('myEl:', myEl);
26
​
27
// Create an element for React to render additional elements into
28
const rootElement = document.createElement('div');
29
// Put that element onto the page
30
document.body.appendChild(rootElement);
31
// Have React render the new JSX element into the root element
32
render(myEl, rootElement);
Copied!

Inline If with Logical '&&' Operator

The && operator can be used as a shorthand of the above example.
If the rendering depends on the existence or value of a particular variable, we can use an inline && to show or hide certain JSX.
The following code uses a property of && such that if the 1st expression is false, JS does not evaluate the 2nd expression, thus does not render the JSX in the 2nd expression.
1
<div>
2
<p>{myRandomNum}</p>
3
{myRandomNum > 5 && <p>Wow! Big numbers!</p>}
4
</div>
Copied!

Inline if-else

We can even express if-else logic concisely inline if our logic is simple.
The following code uses the JavaScript ternary operator.
However, if the condition is too long, the expression will become unreadable, and would be better refactored into code similar to the first example on this page.
(The code below is an example that cannot be directly copy and pasted to test. You will need to define an isLoggedIn variable)
1
<div>
2
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
3
</div>
Copied!
On top of conditionally rendering a specific element and texts, you can use this same logic to place conditions on classes too.
1
<div className={`logged-status ${isLoggedIn ? 'blue' : 'red' }`}>
2
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
3
</div>
Copied!