Rendering Based on Conditions
In React, you can render different UI elements based on conditions using JavaScript expressions inside JSX. The most common patterns are the ternary operator and the logical AND (&&) operator.
You can also use early returns or if/else statements before the return to handle more complex conditions.
Example
function Dashboard({ isLoggedIn, isAdmin, notifications }) {
// Early return pattern
if (!isLoggedIn) {
return <p>Please log in to continue.</p>;
}
return (
<div>
{/* Ternary operator */}
<h1>{isAdmin ? 'Admin Dashboard' : 'User Dashboard'}</h1>
{/* Logical AND — renders only if true */}
{isAdmin && <button>Manage Users</button>}
{/* Conditional with multiple outcomes */}
{notifications.length > 0 ? (
<p>You have {notifications.length} notifications</p>
) : (
<p>No new notifications</p>
)}
</div>
);
} - Ternary: condition ? : — Renders A or B
- Logical AND: condition && — Renders A or nothing
- Early return: if (!condition) return
— Exit early - Avoid using if/else directly inside JSX — use ternary or && instead
Notes
- Be careful with && when the left side could be 0 or an empty string — these are falsy but will render as text. Use Boolean(value) &&
to be safe.
