Conditional Rendering
Overview
In modern applications, the UI is rarely static. You need to show a 'Logout' button if a user is logged in, but a 'Login' button if they aren't. You need to show a spinning loader while data fetches, and a table once it arrives.
In React, because JSX is ultimately just JavaScript, you handle Conditional Rendering using standard JavaScript logic: if/else statements, the ternary operator ? :, and the logical AND && operator.
Because JSX inside a return statement does not support traditional block-level if statements, developers universally rely on ternaries for if/else conditions, and the && operator when they want to render something only if a condition is true (and render absolutely nothing otherwise).
Syntax
function AuthPanel({ isLoggedIn, hasNotifications }) {
// Method 1: Early Return (Standard IF Statement)
// Great for stopping the entire component from rendering
if (isLoggedIn === null) {
return <p>Loading user data...</p>;
}
return (
<div className="panel">
{/* Method 2: Ternary Operator (If / Else) */}
{/* Used for choosing between two distinct UI elements */}
{isLoggedIn ? <LogoutButton /> : <LoginButton />}
{/* Method 3: Logical AND (If True, Do This. Else, Do Nothing) */}
{/* Used when you only want to show an element if a condition is met */}
{hasNotifications && <span className="badge">New Alerts!</span>}
</div>
);
}Common Pitfalls
- The Zero (0) Trap with Logical AND (&&): If you write
{array.length && <List />}and the array is empty (length is 0), React will actually render the number '0' on the screen! This is because in JS, 0 is falsy, so the&&short-circuits and returns 0. To fix this, always make the left side a strict boolean:{array.length > 0 && <List />}.
Interview Questions
JSX is syntactic sugar that compiles into function calls (React.createElement()). You cannot place a block-level if statement inside a function argument in JavaScript. However, you can use expressions like ternaries (? :) because they evaluate to a specific value that can be passed as an argument.
You can return null from the component. If a component returns null, React simply ignores it and renders nothing to the DOM for that specific branch of the tree.
Real-World Example
Data Fetching State UI: This is the exact pattern used in every production application. Early returns cleanly handle loading and error states at the top of the file, while ternaries and logical ANDs handle granular UI toggles within the main layout.
function Dashboard() {
const { data, isLoading, error } = useFetchData('/api/stats');
// 1. Error state (Early return)
if (error) {
return <div className="error-banner">Critical Error: {error.message}</div>;
}
// 2. Loading state (Early return)
if (isLoading) {
return <Spinner className="w-8 h-8 animate-spin" />;
}
// 3. Success state
return (
<main>
<h1>Dashboard Analytics</h1>
{/* Only render the premium chart if the user is a pro tier */}
{data.isProUser && <PremiumChart data={data.charts} />}
{/* Ternary for empty states */}
{data.transactions.length > 0
? <TransactionTable rows={data.transactions} />
: <p className="text-gray-500">No transactions found this month.</p>
}
</main>
);
}Check Your Knowledge
Test your understanding of Conditional Rendering with these quick questions.