react-useportal is a utility React hook for creating and managing React Portals, a feature introduced in React 16 that allows components to render children into a DOM node that exists outside the DOM hierarchy of the parent component. Currently at version 1.0.19, the package simplifies common use cases such as modals, tooltips, dropdowns, and notifications. Key differentiators include built-in isomorphic Server-Side Rendering (SSR) support, full TypeScript compatibility, and a minimal dependency footprint (primarily `use-ssr`). Despite its utility, the project has seen very limited maintenance and updates in recent years, making its release cadence effectively dormant. It aims to abstract away the direct usage of `ReactDOM.createPortal` for a more React-hook-centric API.
npm install react-useportalVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates basic stateless portal usage to `document.body` and a custom target, alongside a stateful example showing how to programmatically open and close a modal-like portal. It includes SSR guards for `document` access.
Evaluate alternatives like `react-portal` (if more actively maintained) or a custom `ReactDOM.createPortal` implementation for long-term projects or those requiring bleeding-edge React features.
Wrap `document` access with `typeof document !== 'undefined'` or similar checks to conditionally execute client-side code, as shown in the quickstart example. This prevents 'document is not defined' errors during SSR.
Consider lazy initialization of portals or creating a single shared portal instance that dynamically updates its content for scenarios with a large number of potential portal triggers. The `programmaticallyOpen` option might also be useful to delay portal creation until needed.
Manually implement WAI-ARIA authoring practices for interactive portal-based components (e.g., modals, tooltips), including focus management (trapping focus, restoring focus), keyboard navigation (Esc key to close), and appropriate ARIA roles and attributes.
Guard `document` access with `typeof document !== 'undefined' ? document.getElementById('my-id') : null` to ensure code runs only in a browser environment.Ensure the target DOM element exists before the portal tries to mount. For dynamically rendered targets, use a `ref` or `useEffect` to ensure the element is ready. For static targets, verify the ID matches an element in your `index.html`.
Use `event.stopPropagation()` on event handlers within the portal's content or on its overlay to prevent events from bubbling up to undesired parent components in the React tree.