Skip to main content

Conditional Rendering

There's no special "if" syntax in JSX — I just use the JavaScript I already have. The only real skill is picking which form reads best.

if / else — when the two branches are big

If the whole return changes, a plain if above the return is the cleanest. Nothing wrong with early returns.

LoginGate.jsx
function LoginGate({ user }) {
if (!user) {
return <SignInScreen />;
}
return <Dashboard user={user} />;
}

return null to render nothing

A component can bail out entirely by returning null. Handy for things that only sometimes exist.

Banner.jsx
function Banner({ message }) {
if (!message) return null;
return <div className="banner">{message}</div>;
}

Ternary — inline, when both sides are small

Inside JSX I reach for ? : when I'm swapping one small thing.

SubmitButton.jsx
<button disabled={isSaving}>
{isSaving ? "Saving…" : "Save"}
</button>

&& — show something or nothing

When there's no "else", && is the shortest thing that works: render the right side only if the left is truthy.

CartBadge.jsx
<button>
Cart
{itemCount > 0 && <span className="badge">{itemCount}</span>}
</button>

The one that bites everyone: put a real boolean on the left of &&. A number 0 is falsy but still renders — React draws "0" on screen.

count-gotcha.jsx
{cart.length && <Cart />}      // renders "0" when the cart is empty
{cart.length > 0 && <Cart />} // fixed — left side is now true/false

Assign to a variable — when the logic gets messy

When there are three-plus states, cramming it into JSX stops being readable. I compute the element above the return and just drop it in.

StatusView.jsx
function StatusView({ status, data }) {
let content;
if (status === "loading") content = <Spinner />;
else if (status === "error") content = <ErrorMsg />;
else content = <List items={data} />;

return <section>{content}</section>;
}

The rule of thumb I settle on: && for show-or-nothing, ternary for swapping one small thing, and the moment it stops reading cleanly inside JSX, pull it out into an if or a variable above the return. Readability wins over cleverness every time.