React Conditional Rendering
React conditional rendering means showing different UI depending on a condition, such as whether a user is logged in or a list is empty. Because JSX is JavaScript, you use normal JavaScript tools: if statements, the ternary operator and the && operator.
Using if Statements
Put an if statement before the return. This is the clearest choice when the outputs are very different.
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h2>Welcome back!</h2>;
}
return <h2>Please sign in.</h2>;
}
<Greeting isLoggedIn={false} />Please sign in.
The Ternary Operator
Inside JSX, use condition ? a : b to choose between two options inline.
function Status({ online }) {
return (
<p>
Server is {online ? <strong>online</strong> : <em>offline</em>}
</p>
);
}
<Status online={true} />Server is online
The Logical && Operator
When you want to show something or nothing, use condition && element. If the condition is false, nothing is rendered.
function Inbox({ unread }) {
return (
<div>
<h3>Inbox</h3>
{unread > 0 && <p>You have {unread} unread messages.</p>}
</div>
);
}
<Inbox unread={3} />Inbox You have 3 unread messages.
Watch out with numbers: if unread is 0, the expression 0 && ... evaluates to 0, and React renders the 0 on the page. Always use a real boolean, such as unread > 0, on the left side.
Returning null
A component can return null to render nothing at all. This is handy for things like alerts that should only sometimes appear.
function Alert({ message }) {
if (!message) return null;
return <div role="alert">{message}</div>;
}(renders nothing when message is empty)
Choosing the Right Approach
- if/else before return — for completely different layouts.
- Ternary — for choosing between two small pieces inline.
- && — for show-or-nothing.
- A variable — compute let content = ... first, then render {content} to keep JSX tidy.
Frequently asked questions
How do I write if else in React JSX?
Use the ternary operator inside JSX, like {isAdmin ? <Admin /> : <User />}, or write a normal if/else before the return statement.
Why does React show 0 on the page?
You used a number with &&, such as {items.length && <List />}. When the length is 0 React renders it. Use {items.length > 0 && <List />} instead.
Is it better to hide an element with CSS or conditional rendering?
Conditional rendering removes the element from the page completely, which is usually what you want. Hiding with CSS keeps it mounted and preserves its state, which can be useful for tabs.