Course contentsShow
← React
Lesson 148 of 2,3965. Lists and KeysFree lesson

Common .map() Mistakes and Fixes

Avoiding pitfalls like returning undefined, forgetting return keywords, or incorrect JSX wrapping.

Common .map() Mistakes and Fixes

What you'll learn: The three most frequent errors developers make when using .map() to render lists, and how to catch them before they cause bugs.

The Core Problem

When you use .map() in JSX, you're essentially creating a new array of React elements. But .map() is easy to break if you're not careful—forgetting a return statement, accidentally returning undefined, or wrapping JSX incorrectly will either crash your component or render nothing at all.

The Three Classic Mistakes

1. Forgetting the Return Keyword (Block Body)

// ❌ WRONG: Nothing renders
const items = data.map((item) => {
  <li>{item.name}</li>
});

// ✅ CORRECT: Explicit return
const items = data.map((item) => {
  return <li>{item.name}</li>;
});

// ✅ CORRECT: Implicit return (no braces)
const items = data.map((item) => <li>{item.name}</li>);

When you use curly braces {}, you need return. Arrow functions without braces automatically return the expression.

2. Returning undefined

// ❌ WRONG: Conditional without else returns undefined
const items = data.map((item) => {
  if (item.visible) {
    return <li>{item.name}</li>;
  }
  // undefined returned here!
});

// ✅ CORRECT: Always return something (or null)
const items = data.map((item) => {
  if (item.visible) {
    return <li>{item.name}</li>;
  }
  return null;
});

3. Incorrect JSX Wrapping

// ❌ WRONG: Adjacent elements without parent
const items = data.map((item) => (
  <dt>{item.term}</dt>
  <dd>{item.definition}</dd>
));

// ✅ CORRECT: Fragment wraps siblings
const items = data.map((item) => (
  <Fragment key={item.id}>
    <dt>{item.term}</dt>
    <dd>{item.definition}</dd>
  </Fragment>
));

Key Takeaway: When .map() renders nothing, check your return statements first, ensure conditionals handle all branches, and wrap multiple JSX elements in a Fragment.