Conditional Rendering in React
Showing and hiding JSX based on state — if statements, ternaries, the && pitfall, and early returns.
2 min read
Since JSX is just JavaScript, conditional rendering doesn't need any special syntax — you use the same tools you'd use to conditionally produce any other value.
if / else with early return
The clearest option when a component should render something completely different based on a condition:
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign in.</h1>;
}The ternary operator, inline
For a smaller choice embedded inside a larger block of JSX, the ternary (? :) keeps things on one expression:
function StatusBadge({ isOnline }) {
return <span>{isOnline ? "🟢 Online" : "⚪ Offline"}</span>;
}&& for "render this, or render nothing"
When there's no else case — you either show something or show nothing — && is the common shorthand, relying on the fact that JSX renders false, null, and undefined as nothing:
function Notifications({ count }) {
return (
<div>
{count > 0 && <span className="badge">{count}</span>}
</div>
);
}The && pitfall with falsy numbers
This shorthand has a sharp edge: JSX renders false as nothing, but it renders 0 as the literal text "0":
function CartCount({ count }) {
return <div>{count && <span>{count} items</span>}</div>;
}
// count = 0 → renders the text "0" on the page, not nothingcount && <span>...</span> evaluates to 0 when count is 0 (short-circuiting on the falsy left side), and React happily renders that 0 as text, since 0 is a valid, renderable value — unlike false. Guard against this by making the condition explicitly boolean:
{count > 0 && <span>{count} items</span>}Storing JSX in a variable
For more complex branching, it's often clearest to just build the JSX in a variable before the return:
function StatusMessage({ status }) {
let message;
if (status === "loading") message = <Spinner />;
else if (status === "error") message = <ErrorText />;
else message = <SuccessText />;
return <div className="status">{message}</div>;
}There's no single "correct" technique — pick whichever reads most clearly for the specific branch you're writing, and prefer early returns when an entire component's output depends on one condition.
The next lesson covers rendering dynamic lists of data, and the key prop React requires for it.