Capítulo 67 de 116

Chapter 67: Fragment

Core Idea

<Fragment> (usually written as the shorthand <>...</>) groups multiple JSX children without adding an extra node to the rendered DOM — the formal API behind the "single root element" rule from Ch 13.

Key Concepts

  • Two syntaxes: the shorthand <>...</> for the common case, and the explicit <Fragment>...</Fragment> for the one situation the shorthand can't handle — passing a key.
  • key on a Fragment: when rendering a list (Ch 17) where each item needs to return multiple sibling elements (not just one), the explicit <Fragment key={id}> form is required, since the shorthand syntax has no way to accept props.
  • No DOM footprint: unlike wrapping in a <div>, a Fragment leaves zero trace in the rendered HTML — useful when an extra wrapper element would break CSS (e.g. flex/grid layouts that depend on direct-child selectors) or semantic HTML structure (e.g. <tr> needing <td> as direct children, not a wrapping <div>).
  • Purely a grouping mechanism — it carries no other props besides the optional key, and has no rendering behavior of its own beyond passing its children through.

Code Examples

function Row({ item }) {
  return (
    <Fragment key={item.id}>
      <td>{item.name}</td>
      <td>{item.value}</td>
    </Fragment>
  );
}
  • What it demonstrates: the explicit Fragment form with a key, needed because this list item returns two sibling <td>s — the shorthand <> couldn't carry the key prop here.

Key Takeaways

  1. Default to the <>...</> shorthand; reach for the explicit <Fragment> form only when a key is needed (multi-element list items).
  2. Fragments exist specifically to avoid unwanted wrapper elements that would break CSS selectors or HTML structural requirements (tables, lists).
  3. A Fragment has no observable effect on the DOM tree — it's purely a JSX-authoring convenience for satisfying the single-root-element rule.

Connects To

  • Ch 13 (Writing Markup with JSX): the single-root-element rule this component satisfies.
  • Ch 17 (Rendering Lists): the multi-element-list-item case that requires the explicit Fragment + key form.