From 183b9a3659671e540e589e96e72c18e678cdaaab Mon Sep 17 00:00:00 2001 From: Mitchell Austin Date: Thu, 21 Sep 2023 23:08:15 -0700 Subject: [PATCH] Call onRequestClose for nested modal when outer modal unmounts --- packages/components/src/modal/index.tsx | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/components/src/modal/index.tsx b/packages/components/src/modal/index.tsx index b46b889a145a88..4b99136c64b56b 100644 --- a/packages/components/src/modal/index.tsx +++ b/packages/components/src/modal/index.tsx @@ -144,14 +144,20 @@ function UnforwardedModal( const dismissers = useContext( context ); const isLevel0 = dismissers === level0Dismissers; + const nestedDismissers = useRef< typeof level0Dismissers >( [] ); // Updates the stack tracking open modals at this level and calls - // onRequestClose for the prior modal if applicable. + // onRequestClose for any prior and/or nested modals as applicable. useEffect( () => { dismissers.push( refOnRequestClose ); const [ first, second ] = dismissers; if ( second ) first?.current?.(); - return () => void dismissers.shift(); + + const nested = nestedDismissers.current; + return () => { + nested[ 0 ]?.current?.(); + dismissers.shift(); + }; }, [ dismissers ] ); // Adds/removes the value of bodyOpenClassName to body element. @@ -344,10 +350,8 @@ function UnforwardedModal( ); - const nextLevelDismissers = useRef( [] ); - return createPortal( - + { modal } , document.body