React Conditional Rendering
If-else, ternary operator, logical AND, and dynamic UI patterns
If-Else
Ternary
&& Operator
Dynamic UI
1. Introduction: Conditional Rendering in React
Conditional rendering in React works the same way conditions work in JavaScript. It allows you to render different UI elements based on different conditions (state, props, or any JavaScript expression).
Analogy: Conditional rendering is like a traffic light. If the light is green, go (render Component A). If it's red, stop (render Component B).
JSX if (isLoggedIn) {
return <Dashboard />;
} else {
return <LoginPage />;
}
Method Best For
If-Else (outside JSX) Complex logic, multiple conditions, early returns
Ternary Operator (? :) Simple two-condition rendering inside JSX
Logical AND (&&) Rendering something OR nothing (one condition only)
Switch Statement Multiple mutually exclusive cases
2. Why Conditional Rendering Matters
Use Case Example
Authentication Dashboard for logged-in users, Login for guests
Loading States Spinner while loading, content when ready
Error Handling Error message if API fails, data if successful
User Roles Admin panel for admins, User view for regular users
Form Validation Error messages only when validation fails
Empty States "No items" when cart is empty
3. If-Else Rendering
3.1 If-Else Outside JSX (Return Early Pattern)
JSX function UserGreeting({ isLoggedIn, username }) {
if (isLoggedIn) {
return <h1>Welcome back, {username}!</h1>;
} else {
return <h1>Please sign in to continue</h1>;
}
}
function UserStatus({ status }) {
if (status === "active") return <p className="active">User is active</p>;
if (status === "suspended") return <p className="suspended">User is suspended</p>;
if (status === "banned") return <p className="banned">User is banned</p>;
return <p className="unknown">Status unknown</p>;
}
3.2 If-Else Inside JSX (Not Possible Directly)
You cannot write if-else directly inside JSX curly braces because JSX only accepts expressions , not statements.
JSX — does NOT work {if (isLoggedIn) {
return <h1>Welcome</h1>;
} else {
return <h1>Login</h1>;
}}
Solution: Use ternary operator or move logic outside JSX.
3.3 If Statements with Variables
JSX function Notification({ message, type }) {
let notificationContent;
if (type === "success") notificationContent = <div className="success">{message}</div>;
else if (type === "error") notificationContent = <div className="error">{message}</div>;
else notificationContent = <div className="info">{message}</div>;
return <div>{notificationContent}</div>;
}
3.4 Multiple If-Else Conditions
JSX function OrderStatusSwitch({ status }) {
switch (status) {
case "pending": return <span>Order placed</span>;
case "processing": return <span>Processing</span>;
case "shipped": return <span>Shipped</span>;
case "delivered": return <span>Delivered</span>;
default: return <span>Unknown status</span>;
}
}
3.5 If-Else with Multiple Return Statements
JSX function PaymentPage({ paymentStatus, amount, errorMessage }) {
if (paymentStatus === "loading") {
return <div><div className="spinner"></div><p>Processing payment...</p></div>;
}
if (paymentStatus === "success") {
return <div><h2>Payment Successful!</h2><p>Amount: ${amount}</p></div>;
}
if (paymentStatus === "error") {
return <div><h2>Payment Failed</h2><p>{errorMessage}</p></div>;
}
return <div><h2>Complete Your Payment</h2><button>Pay Now</button></div>;
}
4. Ternary Operator (? :) Rendering
The ternary operator is a concise way to write if-else inside JSX:
Syntax condition ? expressionIfTrue : expressionIfFalse
4.1 Basic Ternary Syntax
JSX function WelcomeMessage({ isLoggedIn }) {
return (
<h1>{isLoggedIn ? "Welcome back!" : "Welcome, guest! Please sign up."}</h1>
);
}
4.2 Ternary for Simple Conditions
JSX {isVIP ? (
<span className="vip-badge">VIP Member</span>
) : (
<span className="regular-badge">Regular Member</span>
)}
<button className={isDisabled ? "btn-disabled" : "btn-active"}>
{isDisabled ? "Processing..." : children}
</button>
4.3 Ternary with Complex JSX
JSX {user ? (
<>
<img src={user.avatar} alt={user.name} />
<h3>{user.name}</h3>
<button>Edit Profile</button>
</>
) : (
<div>
<p>Please log in to view your profile</p>
<button>Login</button>
</div>
)}
4.4 Nested Ternary Operators
Use with caution — nested ternaries can become hard to read. Consider if-else or switch for complex logic.
JSX {isMember ? (
hasCoupon ? (
<span className="super-sale">${(price * 0.7).toFixed(2)}</span>
) : (
<span className="member-price">${(price * 0.85).toFixed(2)}</span>
)
) : (
<span className="regular-price">${price}</span>
)}
4.5 Ternary for Inline Styling
JSX <div style={{
backgroundColor: type === "error" ? "#ffebee" :
type === "success" ? "#e8f5e9" : "#e3f2fd",
color: type === "error" ? "#c62828" : "#2e7d32"
}}>
{message}
</div>
4.6 Ternary for Attributes
JSX <input
className={isValid ? "input-valid" : "input-invalid"}
placeholder={isValid ? "Looks good!" : "This field has errors"}
disabled={!isValid}
style={{ borderColor: isValid ? "#4caf50" : "#f44336" }}
/>
5. Logical AND (&&) Rendering
The logical AND operator renders something or nothing . If the condition is true, render the element; if false, render nothing.
5.1 Basic && Syntax
JSX {showAlert && (
<div className="alert">{message}</div>
)}
5.2 When to Use && vs Ternary
Use && When... Use Ternary When...
Show something OR nothing Show one thing OR another
Only one possible outcome Two possible outcomes
Simple boolean condition Completely different UI needed
5.3 Common Pitfall: Falsy Values (0, "", NaN)
Bug: When count is 0, {count && ...} renders 0 on screen — not nothing!
JSX // WRONG — renders "0"
{count && <span>You have {count} items</span>}
// CORRECT
{count > 0 && <span>You have {count} items</span>}
{items.length > 0 && <p>Items: {items.length}</p>}
{name !== "" && <p>Name: {name}</p>}
5.4 && for Loading States
JSX {isLoading && <div className="spinner">Loading...</div>}
{error && !isLoading && <div className="error">{error.message}</div>}
{!isLoading && !error && data && (
<div>{data.map(item => <div key={item.id}>{item.name}</div>)}</div>
)}
5.5 && for Error Messages
JSX {errors.email && <span className="error">{errors.email}</span>}
{errors.password && <span className="error">{errors.password}</span>}
5.6 && for Role-Based Access
JSX {user.role === "admin" && (
<div className="admin-panel">
<button>Manage Users</button>
<button>System Settings</button>
</div>
)}
{user.isPremium && (
<div className="premium-features">
<button>Download Reports</button>
</div>
)}
6. Comparison Table: When to Use Each
Method Syntax Use Case
If-Else (outside JSX) if (cond) return AComplex logic, early returns
Ternary cond ? A : BTwo conditions, inline rendering
&& cond && <Comp />Show OR nothing
Switch switch(val)Multiple mutually exclusive cases
Decision Flowchart
Outside JSX? → Use if-else or switch
Inside JSX, one outcome? → Use &&
Inside JSX, two outcomes? → Use ternary
Complex logic? → Move to if-else outside JSX
7. Complete Working Examples
7.1 Example 1: User Dashboard with Authentication
JSX function UserDashboard() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(false);
if (isLoading) {
return <div className="loading-screen"><div className="spinner"></div></div>;
}
return (
<div>
{isLoggedIn && user ? (
<div>
<h2>Welcome back, {user.name}!</h2>
<button onClick={() => setIsLoggedIn(false)}>Logout</button>
{user.role === "admin" && (
<div className="admin-section">
<button>User Management</button>
</div>
)}
</div>
) : (
<LoginForm onLogin={handleLogin} />
)}
</div>
);
}
7.2 Example 2: Shopping Cart with Empty/Full States
JSX function ShoppingCart() {
const [cart, setCart] = useState([...]);
const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
return (
<div>
{cart.length === 0 ? (
<div className="empty-cart">
<h2>Your cart is empty</h2>
<button>Continue Shopping</button>
</div>
) : (
<div>
{cart.map(item => <CartItem key={item.id} item={item} />)}
<span>Total: ${total.toFixed(2)}</span>
{total > 0 && total < 100 && (
<div>Add ${(100 - total).toFixed(2)} more for free shipping!</div>
)}
</div>
)}
</div>
);
}
JSX function RegistrationForm() {
const [formData, setFormData] = useState({ username: "", email: "", password: "" });
const [touched, setTouched] = useState({});
const [submitSuccess, setSubmitSuccess] = useState(false);
if (submitSuccess) {
return <div className="success-screen"><h2>Registration Successful!</h2></div>;
}
const usernameError = getFieldError("username");
return (
<form onSubmit={handleSubmit}>
<input name="username" value={formData.username} onChange={handleChange} onBlur={handleBlur} />
{usernameError && <span className="error-message">{usernameError}</span>}
{touched.password && formData.password && !passwordError && (
<span className="strength-good">Strong password!</span>
)}
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Creating Account..." : "Register Now"}
</button>
</form>
);
}
7.4 Example 4: Toggle Dark/Light Mode
JSX function ThemeSwitcher() {
const [isDarkMode, setIsDarkMode] = useState(false);
return (
<div className={isDarkMode ? "app dark" : "app light"}>
<button onClick={() => setIsDarkMode(!isDarkMode)}>
{isDarkMode ? "Light Mode" : "Dark Mode"}
</button>
<h1>{isDarkMode ? "Dark Theme" : "Light Theme"}</h1>
{isDarkMode && <span className="badge">Dark Optimized</span>}
{!isDarkMode && <span className="badge">Light Optimized</span>}
<button style={{
backgroundColor: isDarkMode ? "#444" : "#f0f0f0",
color: isDarkMode ? "#fff" : "#333"
}}>
Inline ternary styling
</button>
</div>
);
}
8. Common Mistakes and Best Practices
Mistake Problem Solution
{condition && 0}Renders "0" Use condition > 0 &&
Deeply nested ternaries Unreadable Extract to function or if-else
Falsy values with && 0/""/NaN render Convert to boolean explicitly
Complex logic in JSX Hard to maintain Move to helper functions
No default case UI shows nothing Always include fallback
JSX // DO: early returns, explicit booleans, simple ternaries
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage />;
{items.length > 0 && <ItemList />}
{isLoggedIn ? <UserMenu /> : <LoginButton />}
// DON'T: nested ternaries, && with length alone
{cond1 ? (cond2 ? (cond3 ? "A" : "B") : "C") : "D"}
{items.length && <ItemList />}
9. Summary Cheat Sheet
JSX // IF-ELSE (Outside JSX)
if (condition) return <ComponentA />;
else return <ComponentB />;
if (loading) return <Spinner />;
if (error) return <Error />;
return <Content />;
// TERNARY (Inside JSX)
{condition ? "True" : "False"}
{isLoggedIn ? <LogoutButton /> : <LoginButton />}
// LOGICAL AND (Show OR Nothing)
{condition && <Component />}
{count > 0 && <Badge count={count} />}
{error && <ErrorMessage error={error} />}
{isLoading && <Spinner />}
// COMMON PATTERNS
{items.length === 0 ? <EmptyState /> : <ItemList />}
{user.isAdmin && <AdminTools />}
<div className={isActive ? "active" : "inactive"} />
style={{ color: isError ? "red" : "green" }}
Next Steps
Lists and Keys – Rendering arrays with keys
useEffect Hook – Side effects and data fetching
Fragments – Multiple elements without extra DOM nodes
Portals – Rendering outside parent DOM
Error Boundaries – Handling errors in component trees
React Conditional Rendering MCQ Practice
10 Basic MCQs
10 Advanced MCQs
10 Basic React Conditional Rendering MCQs
1
Ternary in JSX: {loggedIn ? <A /> : <B />} is:
A Conditional rendering
B Loop rendering
C Error boundary
D Context
Explanation: Pick one of two UI branches.
2
Logical AND pattern {error && <p>{error}</p>} shows p when:
A error is truthy
B error is 0 always
C error is null always shows
D never
Explanation: Falsy left side renders nothing.
3
To render nothing you can return:
A null
B undefined only in classes
C always <div>
D document
Explanation: null tells React to render no output.
4
if/else before return in component is:
A Valid early return pattern
B Invalid in React
C CSS only
D hooks violation always
Explanation: Use if statements outside JSX freely.
5
Switching many states is cleaner with:
A Object map of components or switch
B 100 nested ternaries only
C SQL
D import css
Explanation: Map status strings to components.
6
{count && <Badge>{count}</Badge>} risk when count is 0:
A Renders 0 on screen
B Renders nothing always
C Throws error
D Shows Badge empty
Explanation: Use count > 0 && or Boolean(count).
7
Loading spinner while fetching often uses:
A isLoading state with conditional JSX
B only CSS :hover
C props immutable
D keys
Explanation: if (loading) return <Spinner />.
8
Inline if in JSX without ternary:
A Use && or extract variable before return
B Use HTML if tag
C Use SQL CASE
D Not possible
Explanation: Cannot use raw if inside JSX expressions.
9
Optional chaining in render: user?.name avoids:
A Crash when user is null
B All re-renders
C Hooks
D CSS
Explanation: Safe access for nested optional data.
10
Parent can conditionally render child with:
A {show && <Child />}
B Child always mounted hidden
C Deleting React
D npm
Explanation: Unmounting removes child state unless preserved.
10 Advanced React Conditional Rendering MCQs
1
Why extract <EmptyState /> component?
A Readability and reuse of conditional UI
B Slower performance always
C Required by React
D Replaces router
Explanation: Named components clarify intent.
2
Suspense boundary is used for:
A Waiting on lazy-loaded components or async UI
B CSS animations only
C Replacing useState
D npm install
Explanation: Show fallback while child suspends.
3
Error boundaries catch:
A Render errors in children
B Event handler errors always
C Async fetch errors automatically
D npm errors
Explanation: Class or library boundaries for render failures.
4
Keeping mounted but hidden vs unmount:
A CSS display:none keeps state; unmount resets state
B No difference ever
C Unmount is faster always
D Hidden runs effects twice
Explanation: Choose based on whether state should persist.
5
Discriminated union status 'idle'|'loading'|'error' helps:
A Exhaustive conditional UI handling
B Remove TypeScript
C Skip keys
D Disable hooks
Explanation: Model states explicitly for safer UI.
6
Portal can render modal while:
A Keeping React tree logical parent
B Breaking event bubbling always
C Removing DOM
D Disabling conditional
Explanation: createPortal renders elsewhere in DOM.
7
Nested ternaries problem:
A Hard to read—prefer early returns or variables
B Required for performance
C Faster than if
D Only way in JSX
Explanation: Refactor for maintainability.
8
React.lazy conditional load:
A Dynamic import with Suspense fallback
B Sync require in render
C CSS import only
D fetch in JSX
Explanation: Code-split heavy components.
9
SSR hydration mismatch often from:
A Conditional render differing server vs client
B Using keys
C Using fragments
D Using props
Explanation: Ensure same markup on server and client.
10
Role attribute for tabs pattern:
A tablist/tab/tabpanel for accessible conditional panels
B div only
C span only
D table only
Explanation: ARIA roles for show/hide sections.
Check All Answers
15 React Conditional Rendering Interview Questions & Answers
Easy
Medium
Hard
1 What is conditional rendering?easy
Answer: Displaying different UI based on state, props, or context (if/ternary/&&).
2 Ternary vs logical && — when to use each?easy
Answer: Ternary for either/or; && when you only render something or nothing.
3 Why does {0 && <Component />} show 0?medium
Answer: Because 0 is falsy but still a valid React child that renders as text.
4 Can you use if inside JSX curly braces?easy
Answer: No—use ternary, &&, or assign to variable before return.
5 How to show loading and error states?medium
Answer: Use state flags (isLoading, error) and return appropriate JSX branches.
6 What is an early return?medium
Answer: Returning different JSX before main render based on condition (e.g. not authorized).
7 How does Suspense help conditional UI?hard
Answer: Shows fallback UI while lazy children or async boundaries are not ready.
8 Error boundary vs try/catch in render?hard
Answer: Error boundaries catch child render errors; try/catch works in event handlers/async code.
9 Unmount vs hide component?medium
Answer: Unmount destroys state; hiding with CSS keeps component mounted and state alive.
10 Pattern for multiple route-like views without router?medium
Answer: State variable switching which component to render (simple apps).
11 Optional chaining in conditional render?easy
Answer: Use user?.profile?.name to avoid errors when intermediate values are null.
12 How to avoid hydration mismatch?hard
Answer: Do not render client-only values on server; use useEffect for client-only UI.
13 When use React.lazy?hard
Answer: Split large components; load on demand with Suspense fallback.
14 Accessible conditional tabs?hard
Answer: Manage selected index state, roving tabindex, aria-selected on tabs.
15 Guard clause example?medium
Answer: if (!user) return <Login />; before main dashboard JSX.