Conditional Rendering
React lets you render different UI based on conditions. There are several patterns to choose from.
Ternary Operator
The most common inline pattern:
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);
}
Keep ternaries short. Complex logic belongs outside JSX.
Logical AND (&&)
Render something or nothing:
function Mailbox({ unreadMessages }) {
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 && (
<p>You have {unreadMessages.length} unread messages.</p>
)}
</div>
);
}
Gotcha: 0 && <p> renders 0, not nothing. Use length > 0 explicitly.
Early Return
Exit the component before returning JSX:
function UserGreeting({ user }) {
if (!user) return null;
return <h1>Hello, {user.name}!</h1>;
}
Clean and readable for complex conditions.
If/Else Outside JSX
Use when logic is too complex for inline:
function Status({ isLoading, data, error }) {
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
if (!data) return <NoData />;
return <DataView data={data} />;
}
Enum Pattern
Map states to components:
function StatusBadge({ status }) {
const badges = {
active: <span className="green">Active</span>,
pending: <span className="yellow">Pending</span>,
inactive: <span className="red">Inactive</span>,
};
return badges[status] || null;
}
Readability wins over clever one-liners.
Best Practices
- Use early returns — For multiple exclusive conditions
- Ternaries for two options — Keep them short
&&for show/hide — One condition, one element- Enum pattern for many states — Maps are cleaner than switch statements
Common Mistakes
0 && <Component>— Renders0because 0 is falsy but not false- Overly long ternaries — Use if/else for complex logic
- Returning
undefined— Always returnnullfor empty renders - Nesting ternaries — Hard to read; use if/else instead