Use a ternary, not &&
React prints numbers, so {count && <X />} renders “0”. Use a ternary.
From vercel-react-best-practices, rule rendering-conditional-render.
Badge that hides at zero
Step the count down to 0, or press Mark all read.
3
&&Bad
Rendered HTML
{count && <span className="badge">{count}</span>}TernaryGood
Rendered HTML
{count > 0 ? <span className="badge">{count}</span> : null}function Inbox({ count }: { count: number }) {
return (
<div className="inbox">
{count > 0 ? <span className="badge">{count}</span> : null}
</div>
)
}
Which falsy values leak
Pick a value for the condition.
&&Bad
Invoice 1042 paid
Rendered HTML
{value && <Badge />}TernaryGood
Invoice 1042 paid
Rendered HTML
{value ? <Badge /> : null}| Value | value && <Badge /> | value ? <Badge /> : null |
|---|
{value ? <Badge /> : null}
{count > 0 && <Badge />}
{Boolean(ratio) && <Badge />}
An empty search result
Type something that matches nothing, like “zzz”.
&&Bad
Rendered HTML
{results.length && <ul>…</ul>}TernaryGood
Rendered HTML
{results.length > 0 ? <ul>…</ul> : <p>No matches</p>}{results.length > 0 ? (
<ul>
{results.map((r) => <li key={r.id}>{r.name}</li>)}
</ul>
) : (
<p>No matches</p>
)}
Why it matters, pros and cons
Why it matters
a && b returns a when falsy. React skips null and false but prints 0 and NaN.
Pros
- No stray “0” in badges or lists
- Avoids a React Native crash
- The else branch is ready for empty states
Cons
&&is fine when the left side is boolean- Nested ternaries read badly; use an early return
- A linter rule enforces it better than review