Conditional Rendering
Since JSX is just JavaScript, showing different markup based on a condition doesn't need any special React syntax — regular JavaScript expressions handle it.
The ternary operator: either/or
JSX Greeting.jsx
function Greeting({ isLoggedIn }) {
return (
<p>
{isLoggedIn ? "Welcome back!" : "Please log in."}
</p>
);
}
Rendered output
With isLoggedIn={true}: "Welcome back!"
With isLoggedIn={false}: "Please log in."The && operator: render only if true
When there's nothing to show in the "false" case, && is more concise than a ternary with an empty branch:
JSX Inbox.jsx
function Inbox({ unreadCount }) {
return (
<div>
<h2>Inbox</h2>
{unreadCount > 0 && <span className="badge">{unreadCount} new</span>}
</div>
);
}
Rendered output
With unreadCount={3}: an "Inbox" heading followed by
a badge reading "3 new".
With unreadCount={0}: just the "Inbox" heading, no badge.unreadCount > 0 && <span>...</span> works because && evaluates its right side only when the left side is truthy — and React renders nothing at all when a piece of JSX evaluates to false.
Early return for a whole different view
When an entire component looks completely different depending on a condition, returning early is often clearer than nesting a ternary around all the markup:
JSX Page.jsx
function Page({ isLoading, data }) {
if (isLoading) {
return <p>Loading…</p>;
}
return <h1>{data.title}</h1>;
}
Rendered output
With isLoading={true}: "Loading…"
With isLoading={false} and data={{title: "Hi"}}: an h1
reading "Hi"Note: watch out for
&& with a number on the left that could be 0. {"{count && items}"} looks fine when count is 0 as an "empty" state — but 0 is falsy, so React tries to render the number 0 itself, and you'll see a stray "0" appear on the page instead of nothing. Writing count > 0 && ... avoids this.