Conditional rendering — showing different UI
1 min read
Showing different things at different times
Real apps show different UI depending on the situation — a "Login" button if logged out, a profile if logged in; a spinner while loading; an error if something failed. Choosing what to show is conditional rendering.
The good news: it is just normal JavaScript, used inside JSX.
Way 1: if / else (before the return)
For bigger choices, decide before returning:
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please log in.</h1>;
}
Way 2: the ternary (inside JSX)
For a quick either/or inside JSX, use the ternary condition ? a : b:
function Status({ isOnline }) {
return (
<p>{isOnline ? "🟢 Online" : "⚪ Offline"}</p>
);
}
Way 3: && (show only when true)
To show something only if a condition is true (and nothing otherwise), use &&:
function Inbox({ count }) {
return (
<div>
<h1>Inbox</h1>
{count > 0 && <p>You have {count} new messages</p>}
</div>
);
}
If count > 0 is true, the <p> shows. If false, nothing shows.
When to use which?
- Big, multi-line differences →
if/else. - Quick this-or-that → ternary
? :. - Show-or-nothing →
&&.
Conditional rendering is just JavaScript inside JSX.
if/elsefor big choices,? :for either/or,&&for show-if-true.