What are React Fragments and when do you need them?

EasyReact FundamentalsTheory Question

Hint

<></> lets you return multiple elements without adding an extra DOM node

Full Answer

Fragments let you group multiple elements without adding an extra DOM wrapper node.

// ❌ Extra div pollutes the DOM
function TableRow() {
  return (
    <div>         {/* invalid inside <tbody> */}
      <td>Name</td>
      <td>Age</td>
    </div>
  );
}

// ✅ Fragment — no DOM node added
function TableRow() {
  return (
    <>
      <td>Name</td>
      <td>Age</td>
    
  );
}

// Keyed fragments — use the long form syntax (shorthand doesn't support key)
function List({ items }) {
  return items.map(item => (
    <React.Fragment key={item.id}>
      <dt>{item.term}</dt>
      <dd>{item.description}</dd>
    </React.Fragment>
  ));
}
💡 Fragments matter most in table structures (tr/td/th must be direct children) and flexbox/grid layouts where an extra wrapper breaks the CSS.

More React Fundamentals Questions

Practice this in a timed sprint

5 free questions, no signup required