Beginner LevelReact JS & React 19
What are the common patterns for conditional rendering in React (&&, ternary, early return)?
❓ Interview Prompt: Explain conditional rendering: Logical AND (`&&`), ternary operator (`condition ? A : B`), early returns, and avoiding `0` rendering bugs.
React supports standard JavaScript conditional patterns to render different JSX dynamically:
3 Primary Patterns:
1
Ternary Operator: '{isLoggedIn ? <UserMenu /> : <LoginForm />}'
2
Logical AND ('&&'): '{unreadCount > 0 && <Badge count={unreadCount} />}'
3
Early Return: Returning alternative JSX early inside component logic.
⚠️ The Number '0' Bug in '&&':
In '{items.length && <List />}' when 'items.length' is '0', JavaScript evaluates '0 && ...' to '0' and renders the number 0 on the screen! Fix: Use '{items.length > 0 && <List />}'.
Code Implementation Example
jsx
function NotificationBadge({ count, isLoading }) {
// 1. Early Return
if (isLoading) return <span>Loading...</span>;
return (
<div>
{/* 2. Ternary Operator */}
{count > 0 ? <p>You have messages</p> : <p>No messages</p>}
{/* 3. Logical AND (Safe > 0 check to prevent rendering 0) */}
{count > 0 && <span className="badge">{count}</span>}
</div>
);
}💡Conditional rendering patterns and avoiding number 0 rendering bugs.
🎯 Interview Key Takeaway
Avoid {items.length && <List />} bugs by ensuring the left side of && is explicitly a boolean (e.g. items.length > 0).
#Conditional Rendering#Ternary#JSX#Beginner
Back to all React JS & React 19 Questions→