How to Implement Conditional Rendering in React
Conditional rendering in React allows developers to display different user interface elements based on specific states, props, or conditions. This guide provides a direct, practical overview of the most common and effective methods to implement conditional rendering in your React applications, including if-else statements, ternary operators, the logical AND operator, and switch cases.
1. The Ternary Operator
(condition ? x : y)
The ternary operator is the most common way to implement inline if-else conditions inside your JSX. It is compact, easy to read, and ideal for choosing between two different elements.
function WelcomeMessage({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);
}2. The Logical AND Operator
(&&)
When you want to render a component only if a condition is true, and
render nothing if it is false, the logical &&
operator is the cleanest approach.
function NotificationBadge({ unreadMessages }) {
return (
<div>
<h2>Inbox</h2>
{unreadMessages.length > 0 && (
<span className="badge">{unreadMessages.length}</span>
)}
</div>
);
}Note: Ensure the left side of the &&
evaluates to a boolean. If it evaluates to a number like 0,
React will render the 0 on the screen.
3. Standard if-else
Statements
If your conditional logic is complex, you cannot use it directly
inside the JSX return statement. Instead, use standard JavaScript
if-else blocks outside the return statement.
function UserGreeting({ role }) {
if (role === 'admin') {
return <h1>Admin Dashboard</h1>;
} else if (role === 'editor') {
return <h1>Editor Panel</h1>;
} else {
return <h1>Guest View</h1>;
}
}4. Preventing Rendering with
null
Sometimes you want a component to hide itself entirely based on a
prop or state. To prevent a component from rendering, return
null from its render function.
function WarningBanner({ warn }) {
if (!warn) {
return null;
}
return (
<div className="warning">
Warning! Something went wrong.
</div>
);
}5. Switch Case Statements
When dealing with multiple conditional paths (more than three), a
switch statement written before the return block keeps the
code clean and maintainable.
function StatusMessage({ status }) {
switch (status) {
case 'loading':
return <p>Loading...</p>;
case 'success':
return <p>Data loaded successfully!</p>;
case 'error':
return <p>An error occurred. Please try again.</p>;
default:
return null;
}
}