Mystery Boxes - A Beginner's Guide to React Fragments


When returning multiple elements from a component’s render method, they must be wrapped in a single parent DOM node:

// Needs a <div> wrapper
return (
  <div> 
    <ChildA />
    <ChildB />
  </div>
);

This extra wrapper <div> in the DOM is often unwanted. Enter React fragments - a way to group elements without adding extra nodes.

Short Syntax

The simplest fragment syntax is:

return (
  <>
    <ChildA />
    <ChildB />
  </>
);

The <></> syntax declares a React fragment. Fragments let you skip the wrapper <div>.

Keyed Fragments

Fragments can also be keyed to give child elements a context:

function Parent() {
  const items = ['A', 'B', 'C'];
  
  return (
    <MyFragment>
      {items.map(item => <Child key={item} />)} 
    </MyFragment>
  );
}

const MyFragment = React.Fragment;

Keyed fragments are handy for list items that need a context.

Motivation

Fragments were introduced to reduce extra DOM nodes. Some benefits are:

  • Avoid wrapper nodes in DOM tree
  • Semantically group components together
  • Key list items without adding wrappers

This improves render efficiency and semantics.

Usage Tips

  • Use short syntax for inline component groups
  • Key fragments to provide list item context
  • Prefer fragments over wrapper divs
  • Don’t overuse - try to keep components logically grouped

Fragments are a tool for cleaner, more readable component trees.

Summary

  • Fragments let you group elements without a DOM node
  • Provides shorter syntax vs wrapper divs
  • Keyed fragments provide context for lists
  • Improves render efficiency and semantics
  • Use judiciously according to use case

React fragments are a key tool for building component hierarchies. No more mystery boxes!