React Conditional Rendering

If-else, ternary operator, logical AND, and dynamic UI patterns

If-Else Ternary && Operator Dynamic UI

Table of Contents

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).

JSXif (isLoggedIn) { return <Dashboard />; } else { return <LoginPage />; }
MethodBest 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 StatementMultiple mutually exclusive cases

2. Why Conditional Rendering Matters

Use CaseExample
AuthenticationDashboard for logged-in users, Login for guests
Loading StatesSpinner while loading, content when ready
Error HandlingError message if API fails, data if successful
User RolesAdmin panel for admins, User view for regular users
Form ValidationError 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)

JSXfunction 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

JSXfunction 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

JSXfunction 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

JSXfunction 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:

Syntaxcondition ? expressionIfTrue : expressionIfFalse

4.1 Basic Ternary Syntax

JSXfunction 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 nothingShow one thing OR another
Only one possible outcomeTwo possible outcomes
Simple boolean conditionCompletely 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

MethodSyntaxUse Case
If-Else (outside JSX)if (cond) return AComplex logic, early returns
Ternarycond ? A : BTwo conditions, inline rendering
&&cond && <Comp />Show OR nothing
Switchswitch(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

JSXfunction 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

JSXfunction 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> ); }

7.3 Example 3: Form with Validation Messages

JSXfunction 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

JSXfunction 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

MistakeProblemSolution
{condition && 0}Renders "0"Use condition > 0 &&
Deeply nested ternariesUnreadableExtract to function or if-else
Falsy values with &&0/""/NaN renderConvert to boolean explicitly
Complex logic in JSXHard to maintainMove to helper functions
No default caseUI shows nothingAlways 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:

AConditional rendering
BLoop rendering
CError boundary
DContext
Explanation: Pick one of two UI branches.
2

Logical AND pattern {error && <p>{error}</p>} shows p when:

Aerror is truthy
Berror is 0 always
Cerror is null always shows
Dnever
Explanation: Falsy left side renders nothing.
3

To render nothing you can return:

Anull
Bundefined only in classes
Calways <div>
Ddocument
Explanation: null tells React to render no output.
4

if/else before return in component is:

AValid early return pattern
BInvalid in React
CCSS only
Dhooks violation always
Explanation: Use if statements outside JSX freely.
5

Switching many states is cleaner with:

AObject map of components or switch
B100 nested ternaries only
CSQL
Dimport css
Explanation: Map status strings to components.
6

{count && <Badge>{count}</Badge>} risk when count is 0:

ARenders 0 on screen
BRenders nothing always
CThrows error
DShows Badge empty
Explanation: Use count > 0 && or Boolean(count).
7

Loading spinner while fetching often uses:

AisLoading state with conditional JSX
Bonly CSS :hover
Cprops immutable
Dkeys
Explanation: if (loading) return <Spinner />.
8

Inline if in JSX without ternary:

AUse && or extract variable before return
BUse HTML if tag
CUse SQL CASE
DNot possible
Explanation: Cannot use raw if inside JSX expressions.
9

Optional chaining in render: user?.name avoids:

ACrash when user is null
BAll re-renders
CHooks
DCSS
Explanation: Safe access for nested optional data.
10

Parent can conditionally render child with:

A{show && <Child />}
BChild always mounted hidden
CDeleting React
Dnpm
Explanation: Unmounting removes child state unless preserved.

10 Advanced React Conditional Rendering MCQs

1

Why extract <EmptyState /> component?

AReadability and reuse of conditional UI
BSlower performance always
CRequired by React
DReplaces router
Explanation: Named components clarify intent.
2

Suspense boundary is used for:

AWaiting on lazy-loaded components or async UI
BCSS animations only
CReplacing useState
Dnpm install
Explanation: Show fallback while child suspends.
3

Error boundaries catch:

ARender errors in children
BEvent handler errors always
CAsync fetch errors automatically
Dnpm errors
Explanation: Class or library boundaries for render failures.
4

Keeping mounted but hidden vs unmount:

ACSS display:none keeps state; unmount resets state
BNo difference ever
CUnmount is faster always
DHidden runs effects twice
Explanation: Choose based on whether state should persist.
5

Discriminated union status 'idle'|'loading'|'error' helps:

AExhaustive conditional UI handling
BRemove TypeScript
CSkip keys
DDisable hooks
Explanation: Model states explicitly for safer UI.
6

Portal can render modal while:

AKeeping React tree logical parent
BBreaking event bubbling always
CRemoving DOM
DDisabling conditional
Explanation: createPortal renders elsewhere in DOM.
7

Nested ternaries problem:

AHard to read—prefer early returns or variables
BRequired for performance
CFaster than if
DOnly way in JSX
Explanation: Refactor for maintainability.
8

React.lazy conditional load:

ADynamic import with Suspense fallback
BSync require in render
CCSS import only
Dfetch in JSX
Explanation: Code-split heavy components.
9

SSR hydration mismatch often from:

AConditional render differing server vs client
BUsing keys
CUsing fragments
DUsing props
Explanation: Ensure same markup on server and client.
10

Role attribute for tabs pattern:

Atablist/tab/tabpanel for accessible conditional panels
Bdiv only
Cspan only
Dtable only
Explanation: ARIA roles for show/hide sections.

15 React Conditional Rendering Interview Questions & Answers

Easy Medium Hard
1What is conditional rendering?easy
Answer: Displaying different UI based on state, props, or context (if/ternary/&&).
2Ternary vs logical && — when to use each?easy
Answer: Ternary for either/or; && when you only render something or nothing.
3Why does {0 && <Component />} show 0?medium
Answer: Because 0 is falsy but still a valid React child that renders as text.
4Can you use if inside JSX curly braces?easy
Answer: No—use ternary, &&, or assign to variable before return.
5How to show loading and error states?medium
Answer: Use state flags (isLoading, error) and return appropriate JSX branches.
6What is an early return?medium
Answer: Returning different JSX before main render based on condition (e.g. not authorized).
7How does Suspense help conditional UI?hard
Answer: Shows fallback UI while lazy children or async boundaries are not ready.
8Error boundary vs try/catch in render?hard
Answer: Error boundaries catch child render errors; try/catch works in event handlers/async code.
9Unmount vs hide component?medium
Answer: Unmount destroys state; hiding with CSS keeps component mounted and state alive.
10Pattern for multiple route-like views without router?medium
Answer: State variable switching which component to render (simple apps).
11Optional chaining in conditional render?easy
Answer: Use user?.profile?.name to avoid errors when intermediate values are null.
12How to avoid hydration mismatch?hard
Answer: Do not render client-only values on server; use useEffect for client-only UI.
13When use React.lazy?hard
Answer: Split large components; load on demand with Suspense fallback.
14Accessible conditional tabs?hard
Answer: Manage selected index state, roving tabindex, aria-selected on tabs.
15Guard clause example?medium
Answer: if (!user) return <Login />; before main dashboard JSX.