Conditional Rendering
&&, ternary, early return, and null — showing UI based on state
Skills taught: react.conditional-render, react.short-circuit, react.ternary-jsx, react.early-return
Conditional rendering patterns
// Three main patterns for conditional rendering
function UserStatus({ user, isLoading, error }) {
// Pattern 3: Early return for guard conditions
if (isLoading) return <p>Loading...</p>;
if (error) return <p style={{ color: 'red' }}>Error: {error}</p>;
if (!user) return null; // renders nothing
return (
<div>
{/* Pattern 1: && — only render if true */}
{user.isAdmin && <span>⭐ Admin</span>}
<h2>{user.name}</h2>
<p>{user.email}</p>
{/* Pattern 2: ternary — one of two options */}
{user.verified
? <span style={{ color: 'green' }}>✓ Verified</span>
: <span style={{ color: 'orange' }}>⚠ Not verified</span>
}
</div>
);
}
function App() {
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
<UserStatus isLoading={true} />
<UserStatus error="Network timeout" />
<UserStatus user={null} />
<UserStatus user={{ name: 'Alice', email: 'alice@example.com', isAdmin: true, verified: true }} />
<UserStatus user={{ name: 'Bob', email: 'bob@example.com', isAdmin: false, verified: false }} />
</div>
);
}
Warning: Pitfall: `{count &&
Items
}` renders `0` when count is 0 — because 0 is falsy but React renders numbers. Write `{count > 0 && Items
}` or `{!!count && Items
}` to be safe.
Frequently Asked Questions
When should I use ternary vs &&?
Use && when you want to show something only if true, and show nothing otherwise. Use ternary when you have two alternatives (show A or show B). For more than two states, extract a variable or a function before the return statement rather than nesting ternaries.