Portal Target
basic-demo
Usage#
import { usePortal } from '@primereact/headless/portal';
import { createPortal } from 'react-dom';const portal = usePortal();
{
portal.state.mounted && createPortal(<div></div>, document.body);
}usePortal provides SSR-safe mount detection so portaled content renders only on the client. See Primitive for a component-based API.
Features#
- SSR-safe mount flag —
state.mountedstaysfalseduring server rendering and flips totrueafter client mount - Lifecycle callbacks —
onMountedandonUnmountedfire on the corresponding mount boundaries - Portal target agnostic — pair the flag with any DOM node you want to render into
Working with callbacks#
Guard createPortal#
Use state.mounted to skip portal rendering on the server, which avoids hydration mismatches.
const portal = usePortal();
{
portal.state.mounted && createPortal(<div>Portaled content</div>, document.body);
}React to mount/unmount#
Pass onMounted and onUnmounted when you need to run a side effect tied to the portal's lifecycle — locking scroll, syncing analytics, or closing neighbouring UI.
const portal = usePortal({
onMounted: () => lockScroll(),
onUnmounted: () => unlockScroll()
});Portal into a custom container#
Combine state.mounted with a ref to a custom container for portaling into a specific element rather than document.body.
const portal = usePortal();
const [container, setContainer] = React.useState<HTMLElement | null>(null);
<div ref={setContainer} />;
{
portal.state.mounted && container && createPortal(<div>Content</div>, container);
}API#
usePortal#
| Name | Type | Default |
|---|---|---|
onMounted | () => void | — |
| Callback function to invoke when the portal is mounted. | ||
onUnmounted | () => void | — |
| Callback function to invoke when the portal is unmounted. | ||
Accessibility#
No direct keyboard behavior — focus management follows the portaled content. See Primitive for full WAI-ARIA compliance details.