Learning navigation

Code with Animation

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 48

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 let you choose a DOM target outside the original clipping or stacking ancestor. The target's own DOM ancestry and CSS still matter, and a portal does not automatically provide accessible modal behavior.

How to use createPortal

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

Once a browser DOM target exists, include the portal in your JSX: createPortal(<div>My note</div>, targetNode). In a server-rendered application, obtain the DOM target after mounting rather than reading document during the server render.

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

Move DOM, keep React ownership

Move a real note outside a clipped card, change its Context value and send an event through its unchanged React parent.

<Card onClick={observeChildClick}>
  <CourseNote />
</Card>

// Card uses overflow: hidden.

Separate DOM host

Empty: switch to Portal DOM to move the note here.

DOM placement
Inside the clipping card
React ownership
Course provider -> card -> note

React card received 0 sample clicks.

The portal uses a real DOM host outside the clipping card. Context and the sample click follow React ownership. The toolbar dispatches the click; the card handler records it. This is a non-modal lab.

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.