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 usingcreatePortal from the renderer package (e.g., react-dom):
API Signature
Frompackages/react-reconciler/src/ReactPortal.js:19:
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
Modal Dialog
Tooltip Component
Dropdown Menu
Notification System
Portal Keys
Portals support keys for list reconciliation:Best Practices
- Create portal roots in HTML: Define portal target elements in your HTML
- Clean up side effects: Always clean up event listeners and body styles
- Handle accessibility: Include proper ARIA attributes and keyboard navigation
- Manage focus: Trap focus within modals and restore it on close
- Consider z-index: Ensure portal content appears above other elements
-
Handle SSR: Check for
documentexistence 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
- 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