React & State · T215

Why does React render 0 after &&?

The && operator returns an operand, not necessarily a boolean. An empty array has length 0, and React renders that number.

The important bit
Use length > 0 or !!length to produce false for an empty list. React omits false, null and undefined; it does render numeric zero.

Understand it. Then fix it.

The useful part

The && operator returns an operand, not necessarily a boolean. An empty array has length 0, and React renders that number.

Make the rule explicit

Use length > 0 or !!length to produce false for an empty list. React omits false, null and undefined; it does render numeric zero.

const hasItems = items.length > 0;
return hasItems && <Cart items={items} />;

Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.

Save the code excerpts ↓
Read the full transcript

My React cart is empty. Why is there a zero just sitting there? You're using the list length with logical AND. When the length is zero, that expression returns zero. React renders numbers. I thought a false condition meant render nothing. Make the left side a boolean. Length greater than zero, or double NOT on the length. With an empty list, both give false. Logical AND then returns false. React skips false, but renders the number zero. Same cart. Remove the last item. No list. No stray zero. Great. Zero items. One squatter evicted.

Go to the source