diff --git a/.changeset/weak-balloons-search.md b/.changeset/weak-balloons-search.md new file mode 100644 index 00000000000..da2ea95bd71 --- /dev/null +++ b/.changeset/weak-balloons-search.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +Portal avoids useless createElement diff --git a/src/Portal/Portal.tsx b/src/Portal/Portal.tsx index 2c1cf7cf9e1..e8d01bb5998 100644 --- a/src/Portal/Portal.tsx +++ b/src/Portal/Portal.tsx @@ -65,14 +65,18 @@ export const Portal: React.FC> = ({ onMount, containerName: _containerName, }) => { - const hostElement = document.createElement('div') + const elementRef = React.useRef(null) + if (!elementRef.current) { + const div = document.createElement('div') + // Portaled content should get their own stacking context so they don't interfere + // with each other in unexpected ways. One should never find themselves tempted + // to change the zIndex to a value other than "1". + div.style.position = 'relative' + div.style.zIndex = '1' + elementRef.current = div + } - // Portaled content should get their own stacking context so they don't interfere - // with each other in unexpected ways. One should never find themselves tempted - // to change the zIndex to a value other than "1". - hostElement.style.position = 'relative' - hostElement.style.zIndex = '1' - const elementRef = React.useRef(hostElement) + const element = elementRef.current useLayoutEffect(() => { let containerName = _containerName @@ -87,7 +91,6 @@ export const Portal: React.FC> = ({ `Portal container '${_containerName}' is not yet registered. Container must be registered with registerPortal before use.`, ) } - const element = elementRef.current parentElement.appendChild(element) onMount?.() @@ -95,7 +98,7 @@ export const Portal: React.FC> = ({ parentElement.removeChild(element) } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [elementRef]) + }, [element]) - return createPortal(children, elementRef.current) + return createPortal(children, element) }