Conditional Rendering
Conditional Rendering
Conditional rendering in React works exactly the same way conditions work in standard JavaScript. You use JavaScript operators like if statements, the logical && operator, and the ternary operator (? :) to create elements representing the current state, and let React update the UI to match them.
1. if Statements
You can use standard if/else statements outside of your JSX return block to determine what elements to return.
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign up.</h1>;
}
2. Logical && Operator (If True)
You can embed JavaScript expressions in JSX by wrapping them in curly braces. This includes the logical AND (&&) operator.
If the condition is true, the element right after && will appear. If it is false, React ignores it.
function Mailbox({ unreadMessages }) {
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 && (
<h2>You have {unreadMessages.length} unread messages.</h2>
)}
</div>
);
}
⚠️ Important Pitfall: Do not put numbers on the left side of &&.
For example, if you write count && <p>New messages</p>, if count is 0, React will render the 0 to the screen! Always make the left side a boolean (e.g., count > 0 && ...).
3. Ternary Operator (? :) (If-Else)
For inline if-else conditional rendering, the ternary operator is the most concise approach.
function UserStatus({ isLoggedIn }) {
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
It can also be used for larger blocks of JSX:
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={handleLogout} />
) : (
<LoginButton onClick={handleLogin} />
)}
</div>
);
4. Preventing Component from Rendering
In rare cases, you might want a component to hide itself even though it was rendered by another component. To do this, return null instead of its render output.
function WarningBanner({ warn }) {
if (!warn) {
return null; // The component renders absolutely nothing
}
return <div className="warning">Warning!</div>;
}
Interview Questions
Q: What is the danger of using condition && <Component /> if the condition is the number 0?
A: JavaScript evaluates 0 && <Component /> as 0. Because 0 is a falsy value but also a valid React node, React will actually render the text “0” to the DOM instead of rendering nothing. To fix this, always ensure the left side is a pure boolean: !!condition && <Component /> or condition > 0 && <Component />.
Q: What is the difference between returning null vs false in a component for conditional rendering?
A: Practically, there is no difference—both tell React to render nothing. However, returning null is the standard convention for a component that chooses to hide itself.