diff --git a/packages/components/src/modal/index.tsx b/packages/components/src/modal/index.tsx index 596043f67c2ebf..0643bf294be2c3 100644 --- a/packages/components/src/modal/index.tsx +++ b/packages/components/src/modal/index.tsx @@ -35,8 +35,9 @@ import Button from '../button'; import StyleProvider from '../style-provider'; import type { ModalProps } from './types'; -// Used to count the number of open modals. +// Used to track and dismiss the prior modal when another opens. let openModalCount = 0; +let dismissOpenModal: ModalProps[ 'onRequestClose' ]; function UnforwardedModal( props: ModalProps, @@ -104,7 +105,10 @@ function UnforwardedModal( if ( openModalCount === 1 ) { ariaHelper.hideApp( ref.current ); document.body.classList.add( bodyOpenClassName ); + } else if ( openModalCount > 1 ) { + dismissOpenModal(); } + dismissOpenModal = onRequestClose; return () => { openModalCount--; @@ -114,7 +118,7 @@ function UnforwardedModal( ariaHelper.showApp(); } }; - }, [ bodyOpenClassName ] ); + }, [ bodyOpenClassName, onRequestClose ] ); // Calls the isContentScrollable callback when the Modal children container resizes. useLayoutEffect( () => {