@@ -21,7 +21,11 @@ import { createPortal } from "react-dom";
2121 *
2222 * @see Docs https://reach.tech/portal#portal
2323 */
24- const Portal : React . FC < PortalProps > = ( { children, type = "reach-portal" } ) => {
24+ const Portal : React . FC < PortalProps > = ( {
25+ children,
26+ type = "reach-portal" ,
27+ containerRef,
28+ } ) => {
2529 let mountNode = React . useRef < HTMLDivElement | null > ( null ) ;
2630 let portalNode = React . useRef < HTMLElement | null > ( null ) ;
2731 let forceUpdate = useForceUpdate ( ) ;
@@ -33,11 +37,12 @@ const Portal: React.FC<PortalProps> = ({ children, type = "reach-portal" }) => {
3337 // In that case, it's important to append to the correct document element.
3438 const ownerDocument = mountNode . current ! . ownerDocument ;
3539 portalNode . current = ownerDocument ?. createElement ( type ) ! ;
36- ownerDocument ! . body . appendChild ( portalNode . current ) ;
40+ const body = containerRef ?. current || ownerDocument . body ;
41+ body . appendChild ( portalNode . current ) ;
3742 forceUpdate ( ) ;
3843 return ( ) => {
39- if ( portalNode . current && portalNode . current . ownerDocument ) {
40- portalNode . current . ownerDocument . body . removeChild ( portalNode . current ) ;
44+ if ( portalNode . current && body ) {
45+ body . removeChild ( portalNode . current ) ;
4146 }
4247 } ;
4348 } , [ type , forceUpdate ] ) ;
@@ -65,6 +70,12 @@ type PortalProps = {
6570 * @see Docs https://reach.tech/portal#portal-type
6671 */
6772 type ?: string ;
73+ /**
74+ * Optional container ref to render the portal in.
75+ *
76+ * @see Docs https://reach.tech/portal#portal-containerRef
77+ */
78+ containerRef ?: React . RefObject < any > ;
6879} ;
6980
7081if ( __DEV__ ) {
0 commit comments