Conditional Rendering
Rendering UI conditionally with &&, ternary, early return null, JSX variables, and the 0-renders bug.
The core idea#
JSX is just expressions, so conditional rendering is ordinary JS producing React nodes. React renders null, undefined, false, and true as nothing — but not 0 or "" (those are printed). 🎯
function Notifications({ items }) {
if (!items) return null; // early return: render nothing
const empty = items.length === 0;
return (
<div>
{empty ? <Empty /> : <List items={items} />} {/* ternary: either/or */}
{items.length > 0 && <Badge n={items.length} />} {/* && : maybe */}
</div>
);
}
Techniques compared#
| Technique | Use when | Note |
|---|---|---|
cond && <X/> |
Show X or nothing | ⚠️ guard the left side (see below) |
cond ? <A/> : <B/> |
One of two branches | Nesting ternaries hurts readability |
if (...) return null |
Whole component renders nothing | 🟢 cleanest for guard clauses |
| JSX in a variable | Complex multi-branch logic | Compute above return, keep JSX flat |
// 🟢 Variable holding JSX keeps the returned tree readable
let content;
if (status === "loading") content = <Spinner />;
else if (status === "error") content = <Error />;
else content = <Data value={data} />;
return <section>{content}</section>;
⚠️ The count && <X/> bug#
&& returns its left operand when that operand is falsy. If the left side is the number 0, React renders the 0 on screen instead of nothing.
{count && <Cart />} // ⚠️ when count === 0 → renders literal "0"
{count > 0 && <Cart />} // 🟢 coerce to a real boolean
{count ? <Cart /> : null} // 🟢 ternary is unambiguous
{!!items.length && <List/>}// 🟢 double-bang forces boolean
Same trap with empty strings inside && chains — always ensure the left operand is a genuine boolean.
flowchart TD
A["Expression in JSX"] --> B{"Value type?"}
B -->|"null / undefined / true / false"| C["Renders nothing"]
B -->|"0 or empty string"| D["Renders the value ⚠️"]
B -->|"React element"| E["Renders the element"]
Interview Q&A#
Q1. Why does {count && <X/>} render 0 when count is zero?
&& short-circuits and returns the left operand when it is falsy. 0 is falsy but is a valid React child, so React prints 0. Use count > 0 && or a ternary.
Q2. Which falsy values does React skip rendering?
null, undefined, true, and false render as nothing. 0 and "" are rendered as text.
Q3. Ternary vs && — when do you pick each?
Use && for "show this or nothing", and a ternary for "show A or B". A ternary is also the safe choice when the condition might be a number.
Q4. Is early return null different from returning false?
Both render nothing. return null is the idiomatic, explicit signal that a component intentionally renders no output; returning false works but reads as accidental.