Part 04 / Topic 5 of 8
The "0 renders as text" gotcha, reproduced for real
Part 2's section 3 already flagged that && only works safely in JSX when the left side is either real JSX or undefined - never a number. Section 4 above sidesteps this because discountPercent > 0 is already a true boolean. This section shows what happens when a lesson skips that comparison and relies on plain truthiness instead - the single most common React beginner bug in this whole part.
// examples/03_conditional_rendering.jsx
// BROKEN
export function CartCountBroken({ count }) {
return <div className="cart-count">{count && <span>{count} item(s) in cart</span>}</div>;
}
// FIXED
export function CartCountFixed({ count }) {
return <div className="cart-count">{count > 0 && <span>{count} item(s) in cart</span>}</div>;
}
count && <span>...</span> is plain JavaScript short-circuiting: when count is 0, the whole expression evaluates to 0 itself (not to false), because that is what && returns when its left side is falsy. React renders 0 as visible text the same way it renders any other number. Rendering <CartCountBroken count={0} /> and reading the container's actual text content really shows this (React 19.3.1, examples/03_conditional_rendering.test.jsx):
container.querySelector(".cart-count").textContent === "0"
A literal, visible 0 on an empty cart - not a crash, not a warning, just a wrong-looking screen. CartCountFixed's only change is comparing instead of trusting truthiness (count > 0, which is always a real boolean), and the same empty-cart render produces an empty string instead:
container.querySelector(".cart-count").textContent === ""
This is the general rule, not just a cart-count special case: anywhere &&'s left side could legitimately be 0 or "" (a count, a total, a page number), compare it to something (> 0, !== "") instead of handing React the raw value.
Done here? The practice set for Part 4 — including the solutions — is on the part page.