Conditional Rendering
Show or hide UI elements based on state and props
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
React renders whatever JS evaluates to — so all JS patterns work inside JSX.
Ternary operator — if/else: ``jsx {isLoggedIn ? <Dashboard /> : <LoginPage />}
&& short-circuit — only renders if truthy: ``jsx {hasError && <ErrorBanner message={error} />}
Beware the 0 trap! 0 && <X /> renders 0, not nothing: ``jsx {count > 0 && <Badge count={count} />} // safe {count && <Badge />} // renders '0' when count is 0!
if/else outside JSX:
jsx function Alert({ type, message }) { if (type === 'error') return <ErrorAlert message={message} />; if (type === 'warning') return <WarningAlert message={message} />; return <InfoAlert message={message} />; }
Early return null — render nothing: ``jsx function Toast({ visible, message }) { if (!visible) return null; return <div className="toast">{message}</div>; }
Object map for switch-like rendering:
jsx const ICONS = { success: '✓', error: '✗', warning: '⚠' }; <span>{ICONS[status]}</span>
Examples
Loading / error / content pattern
Early returns based on state is clean and readable
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// useEffect would fetch here...
if (loading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
return <Profile user={user} />;
}Multiple conditions with ternary
Nested ternaries work but an object map is often cleaner for 3+ conditions
function StatusBadge({ score }) {
const status = score >= 85 ? 'mastered'
: score >= 60 ? 'learning'
: 'not-started';
return (
<span className={status === 'mastered' ? 'badge-green'
: status === 'learning' ? 'badge-yellow'
: 'badge-grey'}>
{status}
</span>
);
}How well did you understand this?
Next in React
Lists & Keys