React ยท Chapter 23 of 42

Fragments

A React component must return a single root element. Fragments let you group multiple elements without adding an extra wrapper `<div>` to the actual DOM.

You can write `<React.Fragment>` or the shorthand `<>...</>`.

Why use fragments?

Extra wrapper divs can break CSS layouts (like flexbox/grid) or add meaningless nesting to the DOM. Fragments avoid this.

Fragments with keys

When rendering a list of fragments, use the full `<React.Fragment key={id}>` syntax since the shorthand `<>` cannot take a key.

Example 1 (jsx)
function Table() {
  return (
    <>
      <td>Cell 1</td>
      <td>Cell 2</td>
    </>
  );
}
Output
Cell 1 | Cell 2 (no extra wrapping element in the DOM)

The <> shorthand groups two <td> elements without adding a wrapper.

Key points

  • A component must return one root element โ€” fragments help with this.
  • Fragments avoid adding unnecessary wrapper elements to the DOM.
  • Shorthand syntax is `<>...</>`.
  • Use `<React.Fragment key={...}>` when a key is needed in a list.
๐Ÿ’ก Note: Fragments are especially useful for table rows/cells, where wrapper divs would be invalid HTML.

๐Ÿ“ Quick Quiz

1. What is the shorthand fragment syntax?

2. Why use fragments instead of a wrapper div?

3. How do you add a key to a fragment?