diff --git a/packages/react/src/Portal/Portal.features.stories.tsx b/packages/react/src/Portal/Portal.features.stories.tsx index 0dfb807cc7a..46321c7e96e 100644 --- a/packages/react/src/Portal/Portal.features.stories.tsx +++ b/packages/react/src/Portal/Portal.features.stories.tsx @@ -1,6 +1,6 @@ -import React from 'react' +import React, {useEffect} from 'react' import type {Meta} from '@storybook/react-vite' -import {Portal, registerPortalRoot} from './Portal' +import {Portal, PortalContext, registerPortalRoot} from './Portal' import classes from './Portal.stories.module.css' import {clsx} from 'clsx' @@ -81,3 +81,107 @@ export const MultiplePortalRoots: React.FC ) } + +export const WithPortalContext = () => { + const customContainerRef = React.useRef(null) + const overrideContainerRef = React.useRef(null) + const [mounted, setMounted] = React.useState(false) + useEffect(() => { + if (customContainerRef.current instanceof HTMLElement && overrideContainerRef.current instanceof HTMLElement) { + registerPortalRoot(customContainerRef.current, 'custom-portal') + registerPortalRoot(overrideContainerRef.current, 'override-portal') + setMounted(true) + } + }, []) + + return ( + <> +
+

Using PortalContext

+

This story demonstrates how to use PortalContext to control where Portal content is rendered.

+ + {/* Default Portal */} +
+ Default Portal (no context): + {mounted ? ( + +
+ Content in default portal +
+
+ ) : null} +
+ + {/* Portal with Context */} +
+ Portal with PortalContext: + + {mounted ? ( + +
+ Content in custom portal (via PortalContext) +
+
+ ) : null} +
+
+ + {/* Override context with containerName prop */} +
+ Context + containerName prop override: + + {mounted ? ( + +
+ Content overriding context with containerName prop +
+
+ ) : null} +
+
+
+ + {/* Custom portal containers */} +
+ Custom Portal Container: +
+
+ +
+ Override Portal Container: +
+
+ + ) +} diff --git a/packages/react/src/Portal/Portal.tsx b/packages/react/src/Portal/Portal.tsx index 2e262db7aa0..490b901c62a 100644 --- a/packages/react/src/Portal/Portal.tsx +++ b/packages/react/src/Portal/Portal.tsx @@ -72,7 +72,6 @@ export const Portal: React.FC> = ({ }) => { const {portalContainerName} = useContext(PortalContext) const elementRef = React.useRef(null) - const {portalContainerName} = useContext(PortalContext) if (!elementRef.current) { const div = document.createElement('div') // Portaled content should get their own stacking context so they don't interfere