Portal
Renders content in a different part of the DOM tree, outside of the parent component hierarchy. Essential for overlays, modals, and tooltips.
Preview
Toggle portal content
This container has overflow: hidden. Without Portal, content would be clipped.
Common Use Cases
When to use Portal
Modals & Dialogs
Render modals at the top of the DOM to ensure proper stacking and focus management.
Tooltips & Popovers
Break out of overflow containers to display tooltips without clipping.
Dropdown Menus
Render dropdowns outside scroll containers for proper positioning.
Notifications
Fixed position toasts and alerts that need to overlay all content.
How It Works
Portal rendering behavior
Default Behavior
By default, Portal renders its children as a direct child of document.body.
Custom Container
You can specify a custom container element to render into, useful for iframe scenarios or specific DOM hierarchies.
React Context
Despite rendering in a different DOM location, React context and event bubbling work normally through the Portal.
Props
Portal API reference
| Prop | Type | Default | Description |
|---|---|---|---|
children* | React.ReactNode | — | The content to render in the portal |
container | HTMLElement | null | document.body | Container element to render into |
Usage
Import and implementation examples
import { Portal } from '@/components/ui/portal'
// Basic portal (renders to document.body)<Portal> <div className="fixed inset-0 bg-black/50 z-50"> <div className="modal">Modal content</div> </div></Portal>
// Portal to custom containerconst container = document.getElementById('portal-root')<Portal container={container}> <Tooltip>Tooltip content</Tooltip></Portal>
// Conditional rendering with Portal{isOpen && ( <Portal> <Dialog onClose={() => setIsOpen(false)}> <DialogContent>...</DialogContent> </Dialog> </Portal>)}Features
Built-in functionality
- DOM breakout: Render outside parent DOM hierarchy
- Stacking context: Escape z-index and overflow constraints
- Custom container: Target specific DOM elements
- React context preservation: Context and events work normally
- SSR safe: Handles server-side rendering gracefully
Accessibility
Accessibility considerations
ARIA Attributes
Portal content maintains proper ARIA relationshipsFocus management should be handled by overlay componentaria-modal should be set on modal contentKeyboard Navigation
| Key | Action |
|---|---|
| Tab | Should trap focus within modal/overlay |
| Escape | Should close overlay (implement in parent) |
Notes
- Portal is a utility - accessibility depends on content rendered
- Use with Dialog, Sheet, or other accessible overlay components
- Ensure focus is moved to portal content when opened
- Return focus to trigger when portal is closed