From 04e5e06d268ac41af67adf3594c7752fb5761764 Mon Sep 17 00:00:00 2001 From: Chewbacca Date: Fri, 10 Feb 2023 13:49:59 -0500 Subject: [PATCH] Make sure DOM is ready for Portal --- app/soapbox/components/ui/portal/portal.tsx | 28 +++++++++++++++---- app/soapbox/jest/test-helpers.tsx | 30 +++++++++++---------- 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/app/soapbox/components/ui/portal/portal.tsx b/app/soapbox/components/ui/portal/portal.tsx index a635a1c99..25fdfe1fc 100644 --- a/app/soapbox/components/ui/portal/portal.tsx +++ b/app/soapbox/components/ui/portal/portal.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useLayoutEffect, useRef } from 'react'; import ReactDOM from 'react-dom'; interface IPortal { @@ -8,9 +8,27 @@ interface IPortal { /** * Portal */ -const Portal: React.FC = ({ children }) => ReactDOM.createPortal( - children, - document.querySelector('#soapbox') as HTMLDivElement, -); +const Portal: React.FC = ({ children }) => { + const isRendered = useRef(false); + + useLayoutEffect(() => { + if (isRendered.current) { + return; + } + + isRendered.current = true; + }, [isRendered.current]); + + if (!isRendered.current) { + return null; + } + + return ( + ReactDOM.createPortal( + children, + document.getElementById('soapbox') as HTMLDivElement, + ) + ); +}; export default Portal; \ No newline at end of file diff --git a/app/soapbox/jest/test-helpers.tsx b/app/soapbox/jest/test-helpers.tsx index a0ff404ab..05791f4d5 100644 --- a/app/soapbox/jest/test-helpers.tsx +++ b/app/soapbox/jest/test-helpers.tsx @@ -51,21 +51,23 @@ const TestApp: FC = ({ children, storeProps, routerProps = {} }) => { }; return ( - - - - - - - {children} +
+ + + + + + + {children} - - - - - - - + + + + + + + +
); };