An if that picks the output
A component is a function, so an ordinary if can decide what it returns:
function OpenSign({ isOpen }) { if (!isOpen) { return <p>Sorry, we are closed.</p>; } return <p>Come in, we are open!</p>;}export default function App() { return ( <div> <OpenSign isOpen={true} /> <OpenSign isOpen={false} /> </div> );}
Open in React Playground
One component, two props, two different paragraphs. Want to flip them? Open it in the playground, press Run, and
change true to false.
if and an early return
The most readable way to handle “there’s nothing to show yet” is to deal with it first and return early. The rest of the function can then assume the data is there:
function OrderStatus({ order }) { if (!order) { return <p>No order yet. Fancy a coffee?</p>; } return ( <p> Order #{order.id}: {order.drink} for {order.name} </p> );}export default function App() { return ( <div> <OrderStatus /> <OrderStatus order={{ id: 42, drink: 'Latte', name: 'Sam' }} /> </div> );}
Open in React Playground
Without the if, order.id would crash with “Cannot read properties of undefined” on the
first <OrderStatus />. Early returns are great for loading screens, empty lists and “please sign
in” messages. There’s one catch, covered under common mistakes: keep any hooks above the
early return.
Pick the JSX first, then return it
When only part of the output changes, decide that part in a variable before the return. JSX is just a
value, so it can go in a let like anything else:
function Greeting({ hour }) { let message; if (hour < 12) { message = <p>Good morning! The coffee is on.</p>; } else if (hour < 17) { message = <p>Good afternoon. Tea time?</p>; } else { message = <p>We are closed. See you at 7am.</p>; } return ( <section> <h3>At {hour}:00</h3> {message} </section> );}export default function App() { return ( <div> <Greeting hour={9} /> <Greeting hour={20} /> </div> );}
Open in React Playground
The heading is shared and only the message changes. With three or more cases this reads better than a chain of
ternaries, and you can add a console.log in any branch while you debug.
The && operator: show it or show nothing
Inside JSX you can’t write an if, but you can write an expression. && is the
short one for “show this only when …”:
function Receipt({ total, isMember }) { return ( <div> <p>Total: ${total.toFixed(2)}</p> {isMember && <p>Member discount applied.</p>} </div> );}export default function App() { return ( <> <Receipt total={7.6} isMember={true} /> <Receipt total={3.8} isMember={false} /> </> );}
Open in React Playground
In JavaScript, a && b gives b when a is true, and gives
a itself when it isn’t. So the member gets the paragraph, and for everyone else the expression is
false, which React draws as nothing. React also draws nothing for null,
undefined, true and an empty string. Numbers are a different story.
The 0 trap
This one shows up in nearly every React codebase at some point. A count of zero should hide the message, and instead a lone 0 appears on the page:
function Inbox({ count }) { return ( <div> <h3>Inbox</h3> {count && <p>You have {count} new messages.</p>} </div> );}export default function App() { return <Inbox count={0} />;}
Open in React Playground
0 && … gives 0, and 0 is a number, so React prints it. (NaN does
the same and prints “NaN”.) Make the left side a real true or false:
function Inbox({ count }) { return ( <div> <h3>Inbox</h3> {count > 0 && <p>You have {count} new messages.</p>} </div> );}export default function App() { return <Inbox count={0} />;}
Open in React Playground
count > 0 is the clearest fix. !!count && … and
Boolean(count) && … work too, as does count ? … : null. The same trap catches
items.length && <List />, so make that items.length > 0.
The ternary: this or that
When there are two things to choose between, use condition ? a : b. It works for whole elements and
for bits of text:
function StockLine({ item, inStock }) { return ( <p> {item}: {inStock ? <strong>in stock</strong> : <em>sold out, back tomorrow</em>} </p> );}export default function App() { return ( <div> <StockLine item="Oat milk" inStock={true} /> <StockLine item="Almond milk" inStock={false} /> </div> );}
Open in React Playground
Ternaries can be nested, and that’s where they stop being friendly:
function Size({ ml }) { return <p>{ml < 250 ? 'Small' : ml < 400 ? 'Medium' : 'Large'}</p>;}
It runs fine, and <Size ml={300} /> says Medium. But a third level, or real JSX in each
branch, gets hard to follow quickly. Move the decision above the return with
if/else (like the Greeting example), or use one of the patterns for
several views below.
Returning null
A component can decide to show nothing at all by returning null. That works well for things like banners,
where the parent shouldn’t need to know the rules:
import { useState } from 'react';function OfferBanner({ show, onClose }) { if (!show) return null; return ( <div className="banner"> Free cookie with every latte today! <button onClick={onClose}>Close</button> </div> );}export default function App() { const [showOffer, setShowOffer] = useState(true); return ( <main> <OfferBanner show={showOffer} onClose={() => setShowOffer(false)} /> <h1>Menu</h1> {!showOffer && <button onClick={() => setShowOffer(true)}>Show the offer again</button>} </main> );}
Open in React Playground
Close the banner and it disappears; the button brings it back. Two things to know about null. The
component still runs, so its hooks run too, even when it shows nothing. And returning undefined (a
missing return) also shows nothing without an error since React 18, which can hide a forgotten
return. Write return null when you mean it.
Several views: switch or an object
A status with three or four values (brewing, ready, failed) is too much for a ternary. A switch in a
small component keeps each case on its own line:
import { useState } from 'react';function OrderMessage({ status, name }) { switch (status) { case 'brewing': return <p>Brewing your order...</p>; case 'ready': return <p>{name}, your latte is ready!</p>; case 'failed': return <p>Sorry, the machine broke. Please ask at the counter.</p>; default: return null; }}export default function App() { const [status, setStatus] = useState('brewing'); return ( <div> {['brewing', 'ready', 'failed'].map((s) => ( <button key={s} onClick={() => setStatus(s)} disabled={s === status}> {s} </button> ))} <OrderMessage status={status} name="Sam" /> </div> );}
Open in React Playground
The default: return null covers a status you didn’t plan for. If each view is its own component, an
object that maps each status to a component is even shorter:
import { useState } from 'react';function Brewing() { return <p>Brewing your order...</p>;}function Ready({ name }) { return <p>{name}, your latte is ready!</p>;}function Failed() { return <p>Sorry, the machine broke. Please ask at the counter.</p>;}const SCREENS = { brewing: Brewing, ready: Ready, failed: Failed };export default function App() { const [status, setStatus] = useState('brewing'); const Screen = SCREENS[status]; return ( <div> {Object.keys(SCREENS).map((s) => ( <button key={s} onClick={() => setStatus(s)} disabled={s === status}> {s} </button> ))} <Screen name="Sam" /> </div> );}
Open in React Playground
SCREENS[status] picks the component, and putting it in a variable with a capital letter
(Screen) lets you use it as a tag. With a lowercase name, JSX would treat it as an HTML tag called
“screen”. Adding a fourth status is now one line in the object.
Conditional classes and attributes
Often you don’t want to swap the element, just its look. A ternary in className does that:
import { useState } from 'react';const TABS = ['Coffee', 'Tea', 'Cakes'];export default function MenuTabs() { const [active, setActive] = useState('Coffee'); return ( <div> {TABS.map((tab) => ( <button key={tab} className={tab === active ? 'tab active' : 'tab'} aria-pressed={tab === active} onClick={() => setActive(tab)} > {tab} </button> ))} <p>Showing the {active.toLowerCase()} menu.</p> </div> );}
Open in React Playground
The active tab gets tab active, the rest get tab, and the CSS does the rest.
aria-pressed tells screen readers which tab is on, so the state isn’t only shown by color. When
several classes can each be on or off, build a list and join it:
function DrinkCard({ name, soldOut, isNew }) { const className = ['card', soldOut && 'sold-out', isNew && 'new'].filter(Boolean).join(' '); return ( <p className={className} title={soldOut ? 'Back tomorrow' : undefined}> {name} {isNew && ' (new)'} </p> );}export default function App() { return ( <div> <DrinkCard name="Latte" /> <DrinkCard name="Iced mocha" isNew /> <DrinkCard name="Pumpkin latte" soldOut /> </div> );}
Open in React Playground
.filter(Boolean) drops the false entries, so there are no stray spaces or the word
“false” in the class. Many projects use a tiny helper package such as clsx for the same job. Attributes
follow the same rule as content: title={soldOut ? 'Back tomorrow' : undefined} leaves the attribute
out completely when the value is undefined, and disabled={false} leaves out
disabled.
Hiding vs removing: what happens to state
When a condition turns false, && and the ternary don’t hide the component. They remove it, and
React throws its state away. Show it again and it starts fresh. This demo has three notes that are hidden in three
different ways:
import { Activity, useState } from 'react';function NotePad({ label }) { const [text, setText] = useState(''); return ( <label> {label} <textarea value={text} onChange={(e) => setText(e.target.value)} rows={2} /> </label> );}export default function App() { const [open, setOpen] = useState(true); return ( <div> <button onClick={() => setOpen(!open)}>{open ? 'Hide' : 'Show'} the notes</button> {/* 1. Removed from the page: its state is thrown away */} {open && <NotePad label="Note 1 (&&)" />} {/* 2. Still on the page, just hidden: its state stays */} <div hidden={!open}> <NotePad label="Note 2 (hidden)" /> </div> {/* 3. Hidden by React, state kept, effects paused */} <Activity mode={open ? 'visible' : 'hidden'}> <NotePad label="Note 3 (Activity)" /> </Activity> </div> );}
Open in React Playground
Run it, type something in all three, then click Hide and Show. Note 1 comes back empty, because
&& unmounted it. Note 2 kept its text: the hidden attribute only hides it, the
component never left. Note 3 uses <Activity>, which React added in version 19.2. It hides the
content too and keeps the state, and on top of that it runs the cleanup of the component’s effects while it’s
hidden and sets them up again when it’s shown, so a hidden timer doesn’t keep ticking.
Neither is always right. Removing is simpler and frees memory, and it’s what you want for a dialog that should open
clean every time. Hiding is better for tabs, where people expect a half-filled form to still be there when they come
back. And if you ever want to reset a component on purpose, give it a new key:
<NotePad key={customerId} /> starts over whenever the customer changes.
Common mistakes
- An if inside the JSX.
<p>{if (open) { … }}</p>is a syntax error, because only expressions can go in braces. Use&&, a ternary, or move theifabove thereturn. - A number on the left of &&.
{count && …}prints 0. Compare first:{count > 0 && …}. - A hook after an early return. The hook runs on some renders and not others, which breaks the rules of hooks:
import { useState } from 'react';function Tip({ total }) { const [roundUp, setRoundUp] = useState(false); if (total === 0) return null; const [percent, setPercent] = useState(10); // a hook after an early return const tip = (total * percent) / 100; return <p>Tip: ${(roundUp ? Math.ceil(tip) : tip).toFixed(2)}</p>;} - Fix: call both
useStates first, thenif (total === 0) return null;. Whentotaldrops to 0 after the first render, the broken version stops with “Rendered fewer hooks than expected. This may be caused by an accidental early return statement.” - Expecting state to survive. A component removed with
&&or a ternary loses its state. Usehiddenor<Activity>, or keep the state in the parent. - Two components in the same spot.
{isAdmin ? <Form /> : <Form readOnly />}is the same component type in the same place, so React keeps its state whenisAdminchanges. Add differentkeys if you want a fresh one.
Questions people ask
What is conditional rendering in React?
Showing different things depending on a value, using plain JavaScript. A component can return different JSX from an if statement, show something only when a condition is true with {isOpen && <p>Open</p>}, choose between two things with a ternary, or return null to show nothing.
How do I write an if statement inside JSX?
You can’t: only expressions go inside curly braces, so {if (open) { … }} is a syntax error. Use {open && <p>Open</p>} or {open ? <Open /> : <Closed />} inside the JSX, or put a normal if above the return and store the JSX in a variable.
Why does my React component show a 0?
You wrote {count && <p>…</p>} and count is 0. The && operator gives back the 0, and React prints numbers, so a lone 0 appears. Compare first: {count > 0 && <p>…</p>}, or use !!count or a ternary. The same happens with items.length && ….
Should I use && or the ternary operator?
Use && when there is something or nothing: {isMember && <p>Discount applied</p>}. Use the ternary when there are two options: {inStock ? "In stock" : "Sold out"}. For three or more options, an if/else above the return, a switch, or an object that maps each value to a component reads better than nested ternaries.
How do I render nothing in React?
Return null from the component, or use a value React draws as nothing inside JSX: false, null, undefined, true or an empty string. The component still runs when it returns null, so its hooks still run.
How do I add a class conditionally in React?
Use a ternary in className, like className={active ? "tab active" : "tab"}. For several optional classes, build an array and join it: ["card", soldOut && "sold-out"].filter(Boolean).join(" "). Small helper packages such as clsx do the same job.
Why does my component lose its state when I hide it?
Because && and the ternary remove the component from the page, and React throws its state away. To keep it, hide it instead with the hidden attribute or CSS, wrap it in <Activity mode="hidden"> (React 19.2 and later), or keep the state in a parent component.
Can I use a switch statement in React?
Yes, in the component body or a small helper component, not inside the JSX braces. Each case returns its own JSX, and a default case can return null. An object that maps each status to a component, like { ready: Ready, failed: Failed }, is a shorter alternative.