Skip to main content

Overview

Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. This is useful for modals, tooltips, dropdowns, and other UI elements that need to break out of their container’s overflow or z-index context.

Creating Portals

Portals are created using createPortal from the renderer package (e.g., react-dom):

API Signature

From packages/react-reconciler/src/ReactPortal.js:19:
The function returns a portal object:

Basic Portal Example

HTML Setup

Your HTML should include a portal target:

Event Bubbling Through Portals

Even though a portal can be anywhere in the DOM, it behaves like a normal React child in every other way. Events fired from within a portal will bubble up to ancestors in the React tree.

Practical Examples

Tooltip Component

Notification System

Portal Keys

Portals support keys for list reconciliation:
Portals only change the physical placement of the DOM node. The React tree hierarchy remains unchanged, which means:
  1. Context will work as if the portal is still in its original position
  2. Event bubbling follows the React tree, not the DOM tree
  3. Hooks like useContext see the portal as a child of its React parent
This is intentional and provides consistency in React’s component model.

Best Practices

  1. Create portal roots in HTML: Define portal target elements in your HTML
  2. Clean up side effects: Always clean up event listeners and body styles
  3. Handle accessibility: Include proper ARIA attributes and keyboard navigation
  4. Manage focus: Trap focus within modals and restore it on close
  5. Consider z-index: Ensure portal content appears above other elements
  6. Handle SSR: Check for document existence when using portals

Server-Side Rendering

Portals require special handling with SSR:

When to Use Portals

Portals are ideal for:
  • Modal dialogs
  • Tooltips and popovers
  • Dropdown menus
  • Notifications and toasts
  • Floating UI elements
  • Third-party widget integration
Portals may not be needed for:
  • Simple overlays that work with CSS positioning
  • Content that doesn’t need to escape overflow or z-index
  • Server-rendered content that needs SEO

See Also

  • Refs - Managing DOM references