React Conditional Rendering
Conditional rendering means showing different content depending on a condition, such as whether a user is logged in.
Using if
Because components are JavaScript functions, you can use a normal if statement before the return.
Example
function Greeting({ isLoggedIn, name }) {
if (isLoggedIn) {
return <h2>Welcome back, {name}!</h2>;
}
return <h2>Please log in to see your courses.</h2>;
}
<Greeting isLoggedIn={true} name="Ayesha" />
<Greeting isLoggedIn={false} />Welcome back, Ayesha! Please log in to see your courses.
The Ternary Operator
Inside JSX you cannot use if, but you can use the ternary operator condition ? a : b.
Example
function StockLabel({ quantity }) {
return (
<p>
{quantity > 0 ? "In stock: " + quantity + " left" : "Sold out"}
</p>
);
}
<StockLabel quantity={4} />
<StockLabel quantity={0} />In stock: 4 left Sold out
The ternary can also choose between two pieces of JSX:
Example
{isAdmin ? <AdminPanel /> : <StudentPanel />}The && Operator
When you want to show something or nothing, use &&. If the left side is true, React shows the right side.
Example
function Inbox({ unread }) {
return (
<div>
<h2>Messages</h2>
{unread > 0 && <p>You have {unread} new messages.</p>}
</div>
);
}With unread={3} the paragraph appears. With unread={0} it does not.
Be careful with numbers on the left of &&. {count && <p>...</p>} shows a 0 on the page when count is 0. Write a real true/false condition such as count > 0 && instead.
Returning null
A component can return null to render nothing at all.
Example
function Warning({ show, message }) {
if (!show) {
return null;
}
return <div className="warning">{message}</div>;
}Using a Variable
For more complex logic, store JSX in a variable first, then use it in the return.
Example
function ResultCard({ marks }) {
let grade;
if (marks >= 80) {
grade = <strong>A grade, excellent work!</strong>;
} else if (marks >= 60) {
grade = <span>B grade, good effort.</span>;
} else {
grade = <span>Keep practising, you can do it.</span>;
}
return (
<div>
<p>Marks: {marks}</p>
{grade}
</div>
);
}
<ResultCard marks={85} />Marks: 85 A grade, excellent work!
Which One to Use?
| Situation | Best choice |
|---|---|
| Two different results | Ternary a ? b : c |
| Show something or nothing | condition && <X /> |
| Many cases | if / else if before the return |
| Hide the whole component | return null |
Good conditional rendering keeps your JSX easy to read. If a ternary becomes long or nested, move the logic into an if statement or a separate component.
Exercise
Exercise
What does {isOpen && <Menu />} show when isOpen is false?
