Portal & Fragment — React

A Fragment (<>...</>) groups several elements without adding an element to the DOM, so a <dl>, a <tr> and flex layouts stay correct. Inside a map, use…

Your dropdown menu gets cut off at the edge of a card, and z-index: 9999 doesn't help. Somewhere else, a wrapping <div> you added breaks a list of terms. Both problems are about where an element ends up in the DOM.

React has two small tools that decide where an element ends up in the DOM. A Fragment groups several elements without adding a wrapping element. A Portal renders an element into another DOM node (another place in the DOM, such as the <body> element), outside the element that wraps it. But in the React tree (the way components sit inside each other), that element stays a child of the component it is written in. Take a bookshelf. A Fragment is like carrying two books at once in your hands, without putting them in a box first: only the two books arrive on the shelf. A Portal is like leaving one book on the shelf in the next room: the book sits somewhere else, but in your notes it's still part of your collection. In React, a book is an element, the box is a wrapping <div>, and a shelf is a place in the DOM. Your notes are the React tree.

Fragment: a group with no wrapper

A component has to return one element. Do you want to return an <h1> and a <p> side by side? Wrap them in a Fragment:

function App() {
  return (
    <>
      <h1>Title</h1>
      <p>Paragraph</p>
    </>
  )
}

Compare the result in the DOM:

<!-- wrapped in a <div>: an extra element -->
<div><h1>Title</h1><p>Paragraph</p></div>

<!-- with a Fragment: only the content -->
<h1>Title</h1><p>Paragraph</p>

Fragment with a key inside a list

A description list <dl> needs <dt> (term) and <dd> (description) pairs as direct children. Each array item produces two elements, so the pair is wrapped in a Fragment:

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

function App() {
  const items = [
    { term: "JSX", desc: "HTML-like syntax" },
    { term: "Props", desc: "Data from the parent" },
  ]
  return <Glossary items={items} />
}

The result in the DOM, four direct children with no wrapper:

<dl id="glossary">
  <dt>JSX</dt><dd>HTML-like syntax</dd>
  <dt>Props</dt><dd>Data from the parent</dd>
</dl>

Portal: escaping the box that clips

A box with overflow: hidden clips everything inside it that goes past its edges. That includes a position: absolute menu whose position is measured from the box (the box is position: relative). z-index only sets the stacking order (which element shows on top). z-index can't stop the wrapping box from clipping what's inside it. So a menu with z-index: 9999 inside a card with overflow: hidden is still cut off.

The fix: put the menu somewhere else in the DOM, outside the card. That's what createPortal does:

import { createPortal } from "react-dom"

function Menu() {
  return createPortal(
    <ul className="menu">
      <li>Edit</li>
      <li>Share</li>
      <li>Delete</li>
    </ul>,
    document.body
  )
}

function Card() {
  return (
    <div className="card" style={{ position: "relative", overflow: "hidden", height: 110 }}>
      <h3>May Report</h3>
      <Menu />
    </div>
  )
}

Portals are for elements that must show on top of everything: modals, tooltips, dropdowns, and notifications (toasts). A modal is a window that appears on top of the page, and a tooltip is a short note that appears when the pointer is over an element.

Events still follow the React tree

In the DOM, the menu is in <body>. But in the React tree, Menu is still a child of Card. React events travel up (bubble) from a child to its parents through the React tree, not through the DOM tree. In this code, the card has its own onClick:

<div className="card" onClick={() => console.log("Card onClick")}>
  <Menu />
</div>

Click "Edit" in the menu, and the console prints Card onClick, even though in the DOM the menu isn't inside the card. Context also still reaches inside a portal.

⚠️ A rejected key, a leftover div, and a portal with nowhere to go

TL;DR: A Fragment (<>...</>) groups several elements without adding an element to the DOM, so a <dl>, a <tr> and flex layouts stay correct. Inside a map, use <Fragment key={...}> because <> can't take a key. A Portal (createPortal(content, targetNode) from react-dom) renders an element into another DOM node (another place in the DOM), such as document.body. That way the element isn't clipped by a wrapping box that uses overflow: hidden, a problem no z-index can fix. Use a Portal for modals, tooltips and dropdowns. In the React tree (the way components sit inside each other), the element is still a child of the component it is written in, so events travel up to its parent in the React tree.

⚡ Fragment: a group with no wrapper

Write:

function App() {
  return (
    <>
      <h1>Title</h1>
      <p>Paragraph</p>
    </>
  )
}

Meaning: A component has to return one element. A Fragment (<> and </>) groups the <h1> and the <p> without putting an extra element in the DOM. This matters where the children are strictly defined, such as <dl>, <tr> and flex layouts.

⚡ A Fragment with a key

Write:

<Fragment key={item.term}>
  <dt>{item.term}</dt>
  <dd>{item.desc}</dd>
</Fragment>

Meaning: This code sits inside items.map(...), which turns each array item into a pair of <dt> (the term, item.term) and <dd> (the description, item.desc) inside a <dl>. Items made by map need a key. The short form <> can't take a key, so use the long form <Fragment key={...}>.

⚡ Portal: escaping the box

Write:

function Menu() {
  return createPortal(
    <ul className="menu">
      <li>Edit</li>
      <li>Share</li>
      <li>Delete</li>
    </ul>,
    document.body
  )
}
Guess first: <Menu /> is written inside the component Card, and that card has an onClick. But in the DOM, the menu is now a child of <body>. When "Edit" is clicked, does the card's onClick run too?

It does. React events follow the React tree (the way components sit inside each other), not the DOM tree. In the React tree, Menu is still a child of Card.

Meaning: createPortal(content, targetNode) puts its content somewhere else in the DOM, here document.body. So the menu isn't cut off by the card with overflow: hidden. Portals are usually used for elements that must show on top of everything: modals, tooltips, dropdowns and notifications (toasts).

What you will learn