Lesson

React Fragments

10 min reading
Free Course

React Fragments: Returning Multiple Elements Cleanly

Every React component must return a single root JSX node. Wrapping sibling elements in extra <div> containers just to satisfy that rule clutters the browser DOM, breaks Flexbox or CSS Grid spacing, and produces invalid HTML inside tables or definition lists. React Fragments group sibling elements without emitting any wrapper tag into the DOM.

Short Syntax vs Explicit <Fragment>

React offers two ways to write a Fragment. Use empty angle brackets (<>...</>) for everyday grouping, and import Fragment from 'react' whenever you need to pass a key prop inside a .map() loop.

import { Fragment } from 'react';

export function TableRow({ item }) {
  return (
    <>
      <td>{item.sku}</td>
      <td>{item.name}</td>
      <td>${item.price}</td>
    </>
  );
}

export function GlossaryList({ terms }) {
  return (
    <dl>
      {terms.map((term) => (
        <Fragment key={term.id}>
          <dt>{term.word}</dt>
          <dd>{term.definition}</dd>
        </Fragment>
      ))}
    </dl>
  );
}

Why Wrapper <div> Tags Break Layouts

Inside a CSS Grid or Flexbox container, direct children become grid cells or flex items. Inserting an unintended <div> around two <button> elements turns them into a single flex child, breaking alignment and gap spacing. Fragments disappear completely during rendering so <td>, <dt>, and <button> sit directly inside their intended parent.

Common Fragment Mistakes

  • Adding key to Shorthand <>: Writing < key={id}> or <>{...}</> with attributes throws a JSX syntax error. Switch to <Fragment key={id}> when mapping lists.
  • Attaching className or style to <Fragment>: Because a Fragment renders zero DOM elements, it cannot receive CSS classes, ref, or event handlers. Use a semantic tag like <section> or <div> if you need styling.

Frequently Asked Questions

Do React Fragments add any runtime performance overhead?

No. Fragments are lighter than <div> tags because the browser creates fewer real DOM nodes in memory.

Can I nest Fragments inside other Fragments?

Yes, though usually one Fragment at the root of a return block or list iteration is all you need.

When should I use a real HTML container instead of a Fragment?

Use a semantic wrapper like <article>, <section>, or <div> whenever the group needs layout styles, padding, borders, or accessibility landmarks.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
React Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum