5.1 - Conditional Rendering
Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like if
statements, &&
, and ? :
operators.
Conditionally returning JSX
Let’s say you have a PackingList
component rendering several Item
s, which can be marked as packed or not:
function Item({ name, isPacked }) {
return <li className="item">{name}</li>;
}
export default function PackingList() {
return (
<section>
<h1>Elaine's Packing List</h1>
<ul>
<Item
isPacked={true}
name="Keys"
/>
<Item
isPacked={true}
name="Wallet"
/>
</ul>
</section>
);
}
Notice that some of the Item components have their isPacked
prop set to true
instead of false
. You want to add a checkmark (✅) to packed items if isPacked={true}
.
You can write this as an if/else
statement like so:
if (isPacked) {
return <li className="item">{name} ✅ </li>;
}
return <li className="item">{name}</li>;
In the previous example, we have some code repetition. Both of the conditional branches return <li className="item">...</li>
. What if you want to change the className
? You’d have to do it in two places in your code, making it harder to maintain!
Below we will explore different ways to implement the checkmark next to packed items.
Conditional (ternary) operator (? :)
JavaScript has a compact syntax for writing a conditional expression — the conditional operator or “ternary operator”.
// equivalent to the previous example
return (
<li className="item">
{isPacked ? name + ' ✅' : name}
</li>
);
You can read it as “if isPacked
is true, then (?
) render name + ' ✅'
, otherwise (:
) render name
”.
This style works well for simple conditions, but use it in moderation. If your components get messy with too much nested conditional markup, consider extracting child components to clean things up.
Logical AND operator (&&
)
When you want to render some JSX when the condition true and nothing otherwise, you can use the logical AND (&&
) operator.
With&&,
you could conditionally render the checkmark only if isPacked
is true
:
return (
<li className="item">
{name} {isPacked && '✅'}
</li>
);
You can read this as “if isPacked
, then (&&
) render the checkmark, otherwise, render nothing”.
A JavaScript &&
expression returns the value of its right side (in our case, the checkmark) if the left side (our condition) is true
.
Don’t put numbers on the left side of &&
.
Ex:
messageCount && <p>New messages</p>
If messageCount == 0
, you won't want anything to render. However, Javascript will still render a 0
! To fix, make the left side a boolean, like so:
messageCount > 0 && <p>New messages</p>
Conditionally assigning JSX to a variable
You can also just use an if
statement and a variable.
For example:
let itemContent = name;
if (isPacked) {
itemContent = name + " ✅";
}
Then, you can nest the Javascript into the JSX:
<li className="item">
{itemContent}
</li>