Course contentsShow
← React
Lesson 107 of 2,3963. JSX FundamentalsFree lesson

When Fragments Need the key Prop

Using the long-form React.Fragment syntax when mapping over arrays and needing to pass a key attribute.

When Fragments Need the key Prop

You'll learn: When React's Fragment shorthand breaks down and you must use the long-form syntax to satisfy React's list reconciliation requirements.

The Problem: Fragments in Lists

You've learned that <Fragment> (or <>) lets you group elements without adding extra DOM nodes. But there's one scenario where the convenient <> </> shorthand doesn't work: when you're mapping over an array and React needs a key to track each item.

Remember, whenever you render a list, React's reconciliation algorithm requires each top-level element to have a unique key prop. The shorthand syntax doesn't support attributes—including key.

The Solution: Long-Form React.Fragment

When you need to return multiple elements from a .map() without wrapping them in a <div>, use the explicit React.Fragment syntax:

function CommentList({ comments }) {
  return (
    <ul>
      {comments.map(comment => (
        <React.Fragment key={comment.id}>
          <li className="author">{comment.author}</li>
          <li className="text">{comment.text}</li>
        </React.Fragment>
      ))}
    </ul>
  );
}

Each comment renders two <li> elements, but they're grouped in a Fragment that carries the required key. No extra wrapper div pollutes your DOM structure.

When This Matters

  • Lists where each item needs multiple sibling elements
  • Maintaining semantic HTML (like keeping list items direct children of <ul>)
  • CSS layouts where extra wrappers break your grid or flexbox

Think of it like addressing packages: the shorthand <> is an unmarked box—fine when there's only one. But in a warehouse (list) with many boxes, each needs a label (key) so the system knows which is which.

Key Takeaway: Use <React.Fragment key={...}> instead of <> when returning multiple elements inside a .map() or any list scenario requiring keys.