Badges are where the && trap bites. Show a count only when there is one.
What to build
Cart buttons that show a badge with the number of items.
Requirements
- Write
CartButton({ count })returning abuttonwith the classcartcontaining the textCartand, only when count is more than 0, aspanwith the classbadgeholding the count, or9+when the count is more than 9. Apprenders three cart buttons with the counts 0, 3 and 12.
Constraints
The button with 0 must contain no number at all.
Example
The buttons read "Cart", "Cart 3" and "Cart 9+".
Why it works
A boolean condition on the left of && renders nothing when it is false, while a bare 0 would be shown, and capping the label keeps the badge small.
Hints
Hint 1
{count > 0 && <span className="badge">...</span>}, never {count && ...}.
Hint 2
Compute the label first: count > 9 ? "9+" : String(count).
Solution
Show one correct solution (try it yourself first)
function CartButton({ count }) {
const label = count > 9 ? "9+" : String(count);
return (
<button className="cart">
Cart {count > 0 && <span className="badge">{label}</span>}
</button>
);
}
export default function App() {
return (
<div>
<CartButton count={0} />
<CartButton count={3} />
<CartButton count={12} />
</div>
);
}