usePortal
A hook that creates and manages React portals for rendering content outside the normal DOM hierarchy. Perfect for modals, tooltips, popovers, and any floating UI elements that need to break out of their parent container.
Parameters
id
:string
- Unique identifier for the portal’s DOM container element
Returns
Portal
: React component for rendering content in the portalisRendered
:boolean
- Indicates if the portal is currently rendered
Usage
import { usePortal } from '@rhinolabs/react-hooks';
function Modal({ isOpen, onClose, children }) {
const { Portal, isRendered } = usePortal("modal-root");
if (!isOpen) return null;
return (
<Portal>
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content">
{children}
<button onClick={onClose}>Close</button>
</div>
</div>
</Portal>
);
}
Notes
- Handles cleanup on component unmount
- Supports multiple unique portal instances
- Maintains proper event bubbling
- Manages portal lifecycle and state
- Handles dynamic portal creation and removal
Last updated on