Lesson 9 +10 XP

React Fragments (<>)

React Fragments (<>)

As required by JSX syntax rules, components must return a single root element. However, adding unnecessary wrapper <div> elements solely to satisfy this requirement can lead to "DOM bloat" and break CSS layouts like Flexbox or Grid.

Solving DOM Bloat with Fragments

A React Fragment lets you group a list of children without adding extra nodes to the Real DOM.

import { Fragment } from 'react';

// Using full React.Fragment syntax
function TableHeader() {
  return (
    <Fragment>
      <th>Item ID</th>
      <th>Item Name</th>
      <th>Price</th>
    </Fragment>
  );
}

Short Syntax: <> ... </>

React provides a convenient short syntax for Fragments: empty angle brackets <> ... </>.

function AppHeader() {
  return (
    <>
      <h1>Dashboard</h1>
      <p>Welcome back, user!</p>
    </>
  );
}

Keyed Fragments

The short syntax <></> does not accept attributes or keys. If you are rendering a list inside a loop and need to pass a key prop to a Fragment, you must use the explicit <Fragment key={...}> syntax.

import { Fragment } from 'react';

function Glossary({ items }) {
  return (
    <dl>
      {items.map(item => (
        <Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.definition}</dd>
        </Fragment>
      ))}
    </dl>
  );
}

Summary & TL;DR

  • Fragments group sibling elements without adding extra wrapper nodes to the DOM.
  • Use the short syntax <> ... </> for simple grouping.
  • Use <Fragment key={item.id}> when mapping over lists that require a key prop.
  • Fragments help keep HTML clean and avoid breaking flexbox/grid layout structures.