Portals

How to render a component's HTML outside of its parent DOM node to fix layout constraints like overflow or z-index.

React3 min readConcept 25 of 46

What is a Portal?

Normally, when a React component renders HTML, that HTML is placed directly inside the parent component's HTML in the DOM.

createPortal allows you to break this rule. It lets a component stay exactly where it is in the *React Tree*, but 'teleport' its actual HTML to a completely different location in the *DOM Tree* (like attaching it directly to the <body> tag).

The Overflow Problem

Imagine you build a Tooltip component inside a Card. If the Card has overflow: hidden in its CSS, your tooltip will get cut off at the edge of the card.

Similarly, Modals often struggle with z-index stacking contexts if they are deeply nested inside other components.

Portals solve this by letting you mount the Modal or Tooltip HTML at the very top level of the document, completely immune to the parent's CSS constraints.

How to use createPortal

First, import it from react-dom (not react!): import { createPortal } from 'react-dom';

Instead of returning normal JSX, return the portal: return createPortal(<div>My Modal</div>, document.body);

The first argument is your JSX, and the second argument is the actual DOM node where you want it to appear.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary use case for React Portals?
  2. 2If a component uses a Portal to render its HTML into `document.body`, what happens to click events triggered inside the portal?
  3. 3Which package provides the `createPortal` function?

Remember this

  • Portals teleport a component's HTML to a different DOM node.
  • They are used to escape overflow: hidden and z-index issues.
  • The component's logical position in the React tree does NOT change.
  • Events and Context still flow perfectly through the React tree.

Done with this concept?

Mark it complete to track your progress. No login needed.