Fragments

Return multiple elements without adding an extra DOM wrapper.

Syntax<> <Child /> <Child /> </>

A component must return a single root element. When you do not want an extra <div> in the DOM, wrap siblings in a Fragment.

Two forms

  • The short syntax: <>...</>.
  • The full form: <Fragment>...</Fragment>, needed when you must pass a key (e.g. in a list).

Example

Example Β· javascript
import { Fragment } from 'react';

function Row({ label, value }) {
  return (
    <>
      <dt>{label}</dt>
      <dd>{value}</dd>
    </>
  );
}

function Definitions({ items }) {
  return (
    <dl>
      {items.map((item) => (
        <Fragment key={item.id}>
          <dt>{item.label}</dt>
          <dd>{item.value}</dd>
        </Fragment>
      ))}
    </dl>
  );
}

When to use it

  • A table component returns multiple <td> cells from a single component without wrapping them in a <div>, which would break the HTML table structure.
  • A form layout component groups a label and input together to return them from one component without adding an extra wrapper div that would break CSS grid alignment.
  • A breadcrumb component uses Fragment with a key to render separator characters between items inside a map() without introducing any extra DOM nodes.

More examples

Short syntax Fragment

Uses the <> shorthand to return two sibling elements from one component without adding a wrapper to the DOM.

Example Β· jsx
function TwoColumns() {
  return (
    <>
      <aside>Sidebar</aside>
      <main>Content</main>
    </>
  );
}

Table row without wrapper div

Shows Fragment keeping the DOM clean inside a table by avoiding an invalid div wrapper around td elements.

Example Β· jsx
function RowCells({ label, value }) {
  return (
    <>
      <td className="label-cell">{label}</td>
      <td className="value-cell">{value}</td>
    </>
  );
}

function StatsTable({ stats }) {
  return (
    <table>
      <tbody>
        {stats.map(s => <RowCells key={s.id} label={s.name} value={s.count} />)}
      </tbody>
    </table>
  );
}

Fragment with key in a list

Uses the named Fragment import (required when a key prop is needed) to group dt/dd pairs inside a mapped list.

Example Β· jsx
import { Fragment } from 'react';

function DefinitionList({ terms }) {
  return (
    <dl>
      {terms.map(({ id, word, def }) => (
        <Fragment key={id}>
          <dt>{word}</dt>
          <dd>{def}</dd>
        </Fragment>
      ))}
    </dl>
  );
}

Discussion

  • Be the first to comment on this lesson.