In React applications, user interfaces are rarely static. You often need to render a loading spinner while fetching data, display a login form if a user is unauthenticated, or show an error banner if an API call fails. In React, conditional rendering works the exact same way conditions work in regular JavaScript.
Use an if...else block outside your returned JSX when you want to return entirely different layout trees:
function UserGreeting({ isLoggedIn, username }) {
if (isLoggedIn) {
return <h2>Welcome back, {username}! <button>Logout</button></h2>;
} else {
return <h2>Please <a href="/login">Log In</a> to continue.</h2>;
}
}
When toggling small pieces of markup inside a larger layout, the ternary operator (condition ? trueMarkup : falseMarkup) is the cleanest technique:
function ProfileBadge({ isVerified }) {
return (
<div className="profile-container">
<h3>Priya Sharma</h3>
<p>
Account Status: {isVerified ? (
<span style={{ color: '#5dbe59', fontWeight: 'bold' }}>✓ Verified Author</span>
) : (
<span style={{ color: '#ef4444' }}>Unverified Account</span>
)}
</p>
</div>
);
}
When you want to render an element only when a condition is true, and render nothing when it is false, use the logical && operator:
function Mailbox({ unreadMessages }) {
return (
<div className="mailbox-card">
<h2>Inbox Notification</h2>
{/* Renders badge only if unread count is greater than zero */}
{unreadMessages.length > 0 && (
<span className="badge">
You have {unreadMessages.length} new messages!
</span>
)}
</div>
);
}
If a component should be completely hidden based on a prop or state flag, return null:
function WarningBanner({ showWarning, message }) {
// If showWarning is false, render absolutely nothing
if (!showWarning) {
return null;
}
return (
<div className="alert-warning">
<strong>Warning:</strong> {message}
</div>
);
}
Now let us explore how to iterate over data collections and why keys are vital for reconciliation in React Lists & Keys Reconciliation.
Accelerate your React mastery by studying these tightly connected core tutorials:
Handling empty collections and loading skeletons.
Switching visual states based on user interaction.
Rendering fallback screens on unhandled component crashes.