Conditional rendering in React
By Flavio
Published · Updated
Tagged: React
Learn how to conditionally render different JSX in a React component, using the ternary operator for if/else and the && operator when you only need an if.
In a React component JSX you can dynamically decide to output some component or another, or just some portion of JSX, based on conditionals.
There’s no special template syntax for this. You use plain JavaScript: if, the ternary operator, &&, variables, switch.
The ternary operator: if / else
The most common way is probably the ternary operator, right inside the JSX:
const Pet = ({ isDog }) => {
return <div>{isDog ? <Dog /> : <Cat />}</div>
}
If isDog is true, you get <Dog />, otherwise <Cat />.
It works great for small choices. If both branches are big chunks of JSX it gets hard to read, and I’d move to one of the other approaches below.
The && operator: if without else
When you conceptually have an if but not an else, use the && operator. If the expression before it is truthy, you get the expression after it. Otherwise React renders nothing:
const Pet = ({ isDog, isCat }) => {
return (
<>
{isDog && <Dog />}
{isCat && <Cat />}
</>
)
}
A component must return a single element, so I wrapped the two expressions in a fragment (<>...</>).
This works because React skips false, true, null and undefined in JSX. They render as nothing.
Watch out for 0 with &&
This is the most common bug with &&:
const Messages = ({ count }) => {
return <div>{count && <p>You have {count} new messages</p>}</div>
}
When count is 0, you’d expect nothing on the page. Instead you see a 0.
Why? && returns the left side when it’s falsy. 0 && something is 0, not false. And React renders numbers, so it prints 0. The same happens with NaN.
The fix is to make the left side a real boolean:
const Messages = ({ count }) => {
return <div>{count > 0 && <p>You have {count} new messages</p>}</div>
}
!!count && ... or Boolean(count) && ... work too. An empty string '' on the left is fine, React renders it as nothing.
Return early with if
You can’t put an if statement inside JSX, but you can use it before the return. When a whole component changes based on a condition, this is often the clearest option:
const Greeting = ({ user }) => {
if (!user) {
return <p>Please log in</p>
}
return <p>Welcome back, {user.name}</p>
}
Render nothing with null
A component can return null to render nothing at all:
const Banner = ({ show }) => {
if (!show) {
return null
}
return <p>Free shipping this week</p>
}
In current React versions, returning undefined also renders nothing. I still prefer null, because it says “nothing” on purpose.
That said, it’s often clearer to decide in the parent whether to render the component at all ({show && <Banner />}), so whoever reads the parent sees it can be hidden.
Store JSX in a variable
When the logic is more than a one-liner, put the JSX in a variable and use it in the return:
const LoginButton = ({ loggedIn }) => {
let button
if (loggedIn) {
button = <button>Log out</button>
} else {
button = <button>Log in</button>
}
return <nav>{button}</nav>
}
It’s more verbose, but you can use any JavaScript you want to build it.
More than two cases: switch or an object
For several states, a switch with early returns reads well:
const Status = ({ status }) => {
switch (status) {
case 'loading':
return <p>Loading...</p>
case 'error':
return <p>Something went wrong</p>
default:
return <p>Done</p>
}
}
Or you can map values to JSX with an object:
const icons = {
success: <span>✅</span>,
warning: <span>⚠️</span>,
error: <span>❌</span>,
}
const Icon = ({ type }) => icons[type] ?? null
The ?? null handles unknown types, so you render nothing instead of undefined.
Avoid nesting ternaries (a ? <A /> : b ? <B /> : <C />). It works, but nobody enjoys reading it.
Removing a component resets its state
When a condition removes a component from the tree, React throws away its state. If you show it again, it starts from scratch:
{showForm && <ContactForm />}
If the user typed something in the form, toggling showForm off and on clears it.
If you want to keep the state, keep the component rendered and hide it instead:
<div hidden={!showForm}>
<ContactForm />
</div>
There’s also the opposite gotcha. If both branches of a ternary render the same component in the same spot, React treats it as the same component and keeps its state:
{isAdmin ? <Counter label="Admin" /> : <Counter label="User" />}
Switching isAdmin here does not reset the counter. Give each one a different key (<Counter key="admin" ... />) if you want a fresh one.
Want me to talk about your product? You can sponsor this site.