The Zero Trap: 0 Renders Visibly
You'll learn why count && <Component /> can unexpectedly display "0" on your screen, and how to prevent it.
The Problem
When you write count && <Component />, you're relying on short-circuit evaluation. If count is truthy, React renders the component. If it's falsy, React should render nothing, right?
Almost. Here's the trap: the number 0 is falsy in JavaScript, but React renders numbers as text. So when count is 0, the && operator returns 0 (the falsy value), and React displays it on screen as the character "0".
Why This Happens
Remember from earlier lessons: numbers and strings render as text in JSX, while null, undefined, true, and false render as nothing. Zero is a number, so it becomes visible text.
const count = 0;
// ❌ Shows "0" on screen
{count && <div>Items</div>}
// ✅ Shows nothing
{count > 0 && <div>Items</div>}
Think of It Like This
Imagine React as a printer. You hand it values to display. When you give it false, it recognizes "don't print this." But when you give it 0, React thinks "this is a number—print it!"
Solutions
Always convert your condition to a proper boolean:
- Use explicit comparisons:
count > 0 && ... - Double-negate:
!!count && ... - Use ternary:
count ? <Component /> : null
Key Takeaway: The && operator returns the first falsy value, and since 0 is a falsy number, React renders it as text. Always ensure your condition evaluates to a boolean or use explicit comparisons.