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:Modal with Focus Management
Common Use Cases
Modals
Tooltips
Notifications
Dropdown Menus
Implementation Details
ThecreatePortal implementation:
Key Features
- Context Preservation: Portals maintain the React context from their parent
- Event Bubbling: Events bubble through the React tree, not the DOM tree
- Cleanup: Automatically unmounts when the portal component unmounts
- useId Support: Preserves mask for
useIdhook functionality
Event Bubbling
Events bubble through the React component tree, not the DOM tree:Context Inheritance
Portals inherit context from their parent:Best Practices
- Container Management: Ensure the container element exists before creating the portal
- Cleanup: Let Preact handle cleanup - don’t manually remove portal content
- Accessibility: Manage focus and keyboard navigation properly
- Z-Index: Use CSS to control stacking order
- Event Handling: Remember that events bubble through the React tree