Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions packages/portal/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ import { createPortal } from "react-dom";
*
* @see Docs https://reach.tech/portal#portal
*/
const Portal: React.FC<PortalProps> = ({ children, type = "reach-portal" }) => {
const Portal: React.FC<PortalProps> = ({
children,
type = "reach-portal",
nodeContainer,
}) => {
let mountNode = React.useRef<HTMLDivElement | null>(null);
let portalNode = React.useRef<HTMLElement | null>(null);
let forceUpdate = useForceUpdate();
Expand All @@ -32,11 +36,12 @@ const Portal: React.FC<PortalProps> = ({ children, type = "reach-portal" }) => {
// In that case, it's important to append to the correct document element.
const ownerDocument = mountNode.current!.ownerDocument;
portalNode.current = ownerDocument?.createElement(type)!;
ownerDocument!.body.appendChild(portalNode.current);
const container = nodeContainer || portalNode.current!.ownerDocument.body;
container.appendChild(portalNode.current);
forceUpdate();
return () => {
if (portalNode.current && portalNode.current.ownerDocument) {
portalNode.current.ownerDocument.body.removeChild(portalNode.current);
if (portalNode.current && container) {
container.removeChild(portalNode.current);
}
};
}, [type, forceUpdate]);
Expand Down Expand Up @@ -64,6 +69,12 @@ type PortalProps = {
* @see Docs https://reach.tech/portal#portal-type
*/
type?: string;
/**
* Target DOM element to render the portal.
*
* @see Docs https://reach.tech/portal#portal-nodeContainer
*/
nodeContainer?: HTMLElement;
};

if (__DEV__) {
Expand Down
14 changes: 11 additions & 3 deletions website/src/pages/portal.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,11 @@ Renders content inside of a portal at the end of the DOM tree.

#### Portal Props

| Prop | Type | Required |
| ----------------------- | ---- | -------- |
| [`children`](#children) | node | true |
| Prop | Type | Required |
| --------------------------------- | ----------- | -------- |
| [`children`](#children) | node | true |
| [`type`](#type) | string | false |
| [`nodeContainer`](#nodeContainer) | HTMLElement | false |

##### Portal children

Expand All @@ -83,3 +85,9 @@ Any content you want to render inside of the portal.
_Type_: `string` default: `reach-portal`

The DOM element type to render.

##### Portal nodeContainer

_nodeContainer_: `HTMLElement` default: `document.body`

The DOM element container of the portal. If not set the portal will be appended to the body of the document.