Introduction
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.Basic Usage
Props
children
- Type:
React.ReactNode - Default:
undefined
container.
container
- Type:
HTMLElement | (() => HTMLElement | null) - Default:
document.body
container will have the portal children appended to it.
You can also provide a callback, which is called in a React layout effect. This lets you set the container from a ref, and also makes server-side rendering possible.
disablePortal
- Type:
boolean - Default:
false
children will be under the DOM hierarchy of the parent component.
Usage Examples
Rendering to Body
By default, Portal renders todocument.body:
Custom Container
Dynamic Container
Common Use Cases
Modal/Dialog
Tooltip
Dropdown Menu
Server-Side Rendering
Portal supports server-side rendering when using a container callback:Disabling Portal
You can disable the portal behavior for testing or other purposes:- Unit testing
- Storybook stories
- Debugging layout issues
- Avoiding z-index conflicts
Multiple Portals
You can have multiple portals with different containers:Event Bubbling
Portal preserves React event bubbling even though the DOM structure is different:Best Practices
- Use refs for containers: Always use refs when specifying a custom container
- Clean up: Portal automatically cleans up when unmounted
- SSR compatibility: Use container callbacks for SSR
- Z-index management: Be mindful of z-index stacking contexts
- Accessibility: Ensure portaled content maintains proper ARIA relationships
Common Pitfalls
Container Not Ready
Missing Container in SSR
Comparison with React Portal
Material-UI Portal is a wrapper around ReactDOM.createPortal that:- Provides better ref handling
- Supports server-side rendering
- Offers
disablePortaloption - Integrates with Material-UI components
When to Use Portal
Use Portal for:- Modals and dialogs
- Tooltips and popovers
- Dropdown menus
- Notifications and snackbars
- Any UI that needs to escape parent overflow/z-index
- Regular content
- Simple styling needs
- When parent hierarchy is sufficient