Skip to main content

createPortal

Create a portal to continue rendering the vnode tree at a different DOM node. Portals allow you to render children into a DOM node that exists outside the parent component’s DOM hierarchy.

Signature

ComponentChildren
required
The vnode(s) to render in the portal.
ContainerNode
required
The DOM node to render into. Must be a valid DOM element.
VNode<any>
A portal vnode that renders its children into the specified container.

Usage

Basic Portal

Render content into a different DOM node:

Portal with Custom Container

Render into a specific DOM element:

Common Use Cases

Modals

Tooltips

Notifications

Implementation Details

The createPortal implementation:

Key Features

  1. Context Preservation: Portals maintain the React context from their parent
  2. Event Bubbling: Events bubble through the React tree, not the DOM tree
  3. Cleanup: Automatically unmounts when the portal component unmounts
  4. useId Support: Preserves mask for useId hook functionality

Event Bubbling

Events bubble through the React component tree, not the DOM tree:

Context Inheritance

Portals inherit context from their parent:

Best Practices

  1. Container Management: Ensure the container element exists before creating the portal
  2. Cleanup: Let Preact handle cleanup - don’t manually remove portal content
  3. Accessibility: Manage focus and keyboard navigation properly
  4. Z-Index: Use CSS to control stacking order
  5. Event Handling: Remember that events bubble through the React tree

Common Patterns

Portal Manager

Lazy Portal Container

TypeScript

Type your portal components:

Source

Implementation: compat/src/portals.js:1-75