Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Array.length gotcha
// The gotcha
function List({ items }) {
return (
items.length && items.map((item) => <Item key={item.id} item={item} />)
);
}
// What will happen when the length of `items` is 0?
// It'll render a 0 as text in a Text Node, because JSX has to be able
// to render any number. Could you imagine a website that couldn't
// display a 0 because it's falsy?
// Good way #1 - use a ternary
function List({ items }) {
return items.length
? items.map((item) => <Item key={item.id} item={item} />)
: null;
}
// Good way #2 - compare the length to evaluate to a boolean without coercion
function List({ items }) {
return (
items.length > 0 && items.map((item) => <Item key={item.id} item={item} />)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment