1. Why Conditional Rendering?
In web applications, the UI must adapt to different states: showing a loading spinner while fetching questions, displaying an error banner when network fails, or toggling between "Login" and "Logout" buttons.
2. Pattern 1: if...else Statements
Best for early returns when entire component views differ:
function ExamResult({ score, passingScore = 50 }) {
if (score === null) {
return Evaluation pending...
;
}
if (score >= passingScore) {
return Congratulations! You Passed.;
} else {
return Needs Improvement. Try Again.;
}
}
3. Pattern 2: Ternary Operator (condition ? trueJSX : falseJSX)
Ideal for concise inline branching inside JSX:
function TestHeader({ isTimeWarning, remainingSeconds }) {
return (
Final Assessment
{remainingSeconds < 60 ? "Less than 1 min left!" : `Time: ${Math.floor(remainingSeconds / 60)} mins`}
);
}
4. Pattern 3: Logical AND (&&) Operator
Use when you want to render an element only when a condition is true, and render nothing otherwise:
function NotificationBell({ unreadNotifications }) {
return (
🔔
{/* Renders badge only if unread notifications exist */}
{unreadNotifications > 0 && (
{unreadNotifications}
)}
);
}
{messages.length && } if length is 0, because JavaScript evaluates 0 && ... to 0, printing a literal "0" onto the screen. Always use boolean coercion: {messages.length > 0 && }.
5. Preventing Rendering by Returning null
If a component should render nothing at all under certain conditions, return null:
function WarningModal({ isOpen, message }) {
if (!isOpen) return null; // Component does not render
return {message};
}