React Conditional Rendering
Conditional rendering lets a component decide, at render time, which JSX to show based on state, props, or other JavaScript expressions.
Short-Circuiting with the && Operator
The && operator is the most common way to render something only when a condition is true. Because React skips rendering false, null, and undefined, an expression like {isLoggedIn && <WelcomeBanner />} renders nothing when isLoggedIn is false and the JSX when it's true. This reads naturally inline within JSX without needing a separate if statement.
Showing a Notification Badge
function Notifications({ count = 3 }) {
return (
<div>
<h2>Inbox</h2>
{count > 0 && <span className="badge">{count} new</span>}
</div>
);
}
export default Notifications;
Ternaries for Either/Or Output
When you need to render one of two things rather than something-or-nothing, the ternary operator (condition ? a : b) is the cleaner tool. It works as an expression, so it can sit directly inside JSX curly braces, unlike an if/else statement, which cannot be embedded in JSX at all.
Toggling a Button Label
function LoginButton({ isLoggedIn = false, onClick = () => {} }) {
return (
<button onClick={onClick}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
);
}
export default LoginButton;
Early Returns for Whole-Component Branching
When a component has entirely different things to render depending on a condition — a loading spinner, an error message, or the real content — it's often clearest to return early from the function rather than nesting ternaries. Each return statement short-circuits the rest of the function, so only one branch's JSX is ever produced.
Loading, Error, and Success States
function UserProfile({
status = 'success',
user = { name: 'Ada Lovelace', email: 'ada@example.com' },
error = { message: 'Something went wrong' },
}) {
if (status === 'loading') {
return <p>Loading profile...</p>;
}
if (status === 'error') {
return <p className="error">Couldn't load profile: {error.message}</p>;
}
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
export default UserProfile;
- Prefer && for a single optional element, ternaries for two alternatives, and early returns for full-component states.
- Always guard numeric conditions (count > 0) before using && to avoid accidentally rendering 0.
- Keep ternaries inside JSX shallow — extract nested ternaries into a variable or a helper function.
- Remember if/else statements can't live inside JSX; they must sit above the return statement.
Exercise: React Conditional Rendering
Which technique is commonly used inline in JSX to render one of two elements?