Topic 13 of 54
Conditional Rendering
Overview
UIs are dynamic. You want to show a Login button if the user is logged out, and a Logout button if they are logged in. Or maybe show a loading spinner while data fetches. Conditional rendering in React is done entirely using standard JavaScript operators: `if` statements, the logical AND `&&`, and the Ternary operator `? :`.
Syntax
The ternary operator is perfect when you need to render one thing OR another based on a condition.
? :
jsx
function UserPanel({ isLoggedIn, name }) {
// Used for If-Else logic directly inside JSX
return (
<div>
{isLoggedIn ? (
<h1>Welcome back, {name}!</h1>
) : (
<button>Please Log In</button>
)}
</div>
);
}The `&&` operator is ideal when you only want to render an element if a condition is true, and do absolutely nothing if it is false.
&&
jsx
function Notification({ unreadCount }) {
// Used for If-Only logic (render something OR render nothing)
return (
<div>
<h2>Inbox</h2>
{/* If unreadCount > 0 is true, it renders the badge. If false, it renders nothing. */}
{unreadCount > 0 && (
<span className="badge">{unreadCount} New Messages</span>
)}
</div>
);
}Standard `if` statements are used *outside* of the return block to completely bail out of rendering the main component.
If statement
jsx
function Dashboard({ isLoading, error, data }) {
// Used when handling entirely different views (like loading states)
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage msg={error} />;
// If we reach here, we have data
return <DataChart data={data} />;
}Common Pitfalls
- The 'Zero Bug' mentioned in interview tips: `{0 && <Component />}` renders `0`.
- Trying to use a standard `if` statement inside the JSX `{}` brackets. It will throw a syntax error.
Interview Tips
- Beware of the 'Zero Bug' with `&&`. If the condition evaluates to the number `0` (e.g., `messages.length && <p>New</p>`), React will actually render a `0` on the screen! Always force a boolean: `messages.length > 0 && ...`.
Real-World Example
Combining early returns for loading states and ternaries for UI toggles.
example
jsx
function UserSettings({ user, isFetching }) {
if (isFetching) {
return <SkeletonLoader />;
}
if (!user) {
return <Navigate to="/login" />;
}
return (
<div className="settings">
<h2>Settings</h2>
{user.isAdmin && <AdminPanelButton />}
<p>Subscription: {user.isPro ? 'Pro' : 'Free Plan'}</p>
</div>
);
}