Conditional Rendering
In React, you can conditionally render components just like you use conditions in JavaScript. React will only render the parts of the UI that are needed based on the current state.
Pattern 1 โ if / else Before the Return
function LoadingState({ isLoading, error, data }) {
// Early returns keep the happy path clean
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage message={error} />;
if (!data) return <EmptyState />;
// Happy path
return <DataTable rows={data} />;
}
Pattern 2 โ Ternary Operator
function AuthStatus({ isLoggedIn, user }) {
return (
<nav>
{isLoggedIn
? <UserMenu name={user.name} />
: <LoginButton />
}
</nav>
);
}
Pattern 3 โ Logical AND (&&)
When you only want to render something or nothing, use &&.
function Notification({ messages }) {
return (
<div>
<h1>Inbox</h1>
{/* Only renders the badge if there are messages */}
{messages.length > 0 && (
<span className="badge">{messages.length} new</span>
)}
</div>
);
}
WarningBe careful with the && pattern when the left side might be
0. In JSX, 0 renders as the number 0. Use count > 0 && ... or !!count && ... instead of count && ....Pattern 4 โ Switch Statement
function StatusBadge({ status }) {
switch (status) {
case "active": return <span className="badge green">Active</span>;
case "pending": return <span className="badge yellow">Pending</span>;
case "banned": return <span className="badge red">Banned</span>;
default: return <span className="badge grey">Unknown</span>;
}
}
Hiding Components with null
// Return null to render nothing โ the component still mounts/unmounts
function Alert({ message, show }) {
if (!show) return null;
return (
<div className="alert">
{message}
</div>
);
}