react-portal simplifies the creation and management of React Portals, enabling developers to render children into a different part of the DOM tree, outside the parent component's hierarchy. This is particularly useful for modals, tooltips, lightboxes, and notifications that require specific positioning or need to break out of CSS `overflow: hidden` containers. The current stable version is 4.3.0. It leverages React's official Portal API (introduced in React 16) to provide a robust solution. A key differentiator is its dual component approach, offering both a low-level `<Portal />` for maximum control and a `<PortalWithState />` for common stateful interactions (e.g., close on ESC, close on outside click) without external dependencies. Notably, since v4.1.0, it includes a fallback mechanism to support React v15 while primarily targeting React v16 and newer, making it flexible for diverse project ecosystems. It focuses on clean markup, SSR compatibility, and minimalistic design. The project demonstrates an active maintenance cadence, with recent minor releases addressing bugs and ensuring compatibility.
npm install react-portalVerified import paths — ran on the pinned version, not inferred.
Demonstrates both the basic `Portal` and the stateful `PortalWithState` components, showing how to render content into `document.body` or a custom DOM node, and handle portal visibility and interactions like closing on ESC or outside clicks.
Upgrade your project's React and React-DOM versions to 16.0.0 or newer. If maintaining React 15 support is critical, ensure `react-portal` is at least v4.1.0.
Wrap the children of `<Portal>` or `<PortalWithState>` in your own `div` or other element, and apply styling to this wrapper element instead.
Adjust your CSS selectors and component structure if you relied on the `openByClickOn` wrapper div or its className for styling or layout. The clicked element will now appear directly in the DOM.
Structure your `PortalWithState` like this: `<PortalWithState>{({ portal }) => <div>{portal(<p>My content</p>)}</div>}</PortalWithState>`. Do not return the render prop object directly.Upgrade `react` and `react-dom` to at least version 16.0.0. If you must support React 15, upgrade `react-portal` to v4.1.0 or later for its fallback mechanism.
Ensure `Portal` components are only rendered on the client-side, or use conditional rendering based on `typeof document !== 'undefined'` for any custom logic that interacts with the DOM.
The function child of `PortalWithState` must return React elements, and the actual content to be portaled should be passed as an argument to the `portal` render prop function. For example: `{({ openPortal, portal }) => (<button onClick={openPortal}>{portal(<p>Content</p>)}</button>)}`.