It’s Just JavaScript
React has no special conditional syntax — you reach for the same if statements, ternaries, and logical operators you already know from JavaScript, since JSX is just an expression inside a function.
Conditional Rendering with if
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign in.</h1>;
}The Ternary Operator
A ternary is the most common way to choose between two pieces of JSX inline, right inside a larger return statement.
Ternary Inside JSX
function StatusBadge({ isOnline }) {
return (
<span>
{isOnline ? "🟢 Online" : "⚪ Offline"}
</span>
);
}The && Operator for "Render or Nothing"
When there’s no alternative to render, the && operator is a concise way to show something only when a condition is true.
Logical && Rendering
function Inbox({ unreadCount }) {
return (
<div>
<h2>Inbox</h2>
{unreadCount > 0 && <p>You have {unreadCount} unread messages.</p>}
</div>
);
}A Common && Pitfall
If the left side of && is 0 (a falsy number, not false), React will render the literal "0" instead of nothing — because 0 is a valid, renderable JSX child. Guard against this with a comparison like unreadCount > 0 instead of unreadCount alone.
The 0 Pitfall
// Renders "0" on screen if unreadCount is 0 — a common bug!
{unreadCount && <p>You have {unreadCount} unread messages.</p>}
// Fixed: compares to produce an actual boolean
{unreadCount > 0 && <p>You have {unreadCount} unread messages.</p>}Rendering nothing with null
Returning null from a component (or as part of an expression) renders nothing at all — a valid way to conditionally render "no UI."
Returning null
function Banner({ dismissed }) {
if (dismissed) {
return null;
}
return <div className="banner">Welcome!</div>;
}Best Practice
Extract complex conditional JSX into its own variable or small component when a ternary or && chain starts feeling hard to read — clarity beats cleverness in JSX.