Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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",
containerRef,
}) => {
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 body = containerRef?.current || ownerDocument.body;
body.appendChild(portalNode.current);
forceUpdate();
return () => {
if (portalNode.current && portalNode.current.ownerDocument) {
portalNode.current.ownerDocument.body.removeChild(portalNode.current);
if (portalNode.current && body) {
body.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;
/**
* Optional container ref to render the portal in.
*
* @see Docs https://reach.tech/portal#portal-containerRef
*/
containerRef?: React.RefObject<any>;
};

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 |
| [`containerRef`](#containerRef) | ref | 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 containerRef

_containerRef_: `ref` default: `document.body`

Ref to the container in where to render the portal. If not set the portal will be appended to the body of the document.