I am using Material UI ModalUnstyled
Currently, when the ‘showSpinner’ prop is true
, a <Spinner />
overlays the modal content. The problem is: When the user clicks on the backdrop
of the Modal, the backdrop closes… I do not want this to happen and I am not sure how to prevent this
export const Modal = ({
children,
show,
onClickClose,
showSpinner,
}: ModalProps) => {
const ariaForId = `:modal-id-aria-${guidGenerator()}:`
const BackdropUnstyled = React.forwardRef<
HTMLDivElement,
{ open?: boolean; className: string }
>((props, ref) => {
// @ts-ignore
// https://github.com/mui/material-ui/issues/32882
const {ownerState, open, className, ...other} = props;
return <div
className={clsx({'MuiBackdrop-open': open}, 'modal-backdrop', className)}
ref={ref}
{...other}>
<BlurOverlay onClick={!showSpinner ? onClickClose : () => {}}/>
</div>
});
return <ModalUnstyled
aria-labelledby={ariaForId}
aria-describedby={ariaForId}
open={show}
onClose={!showSpinner ? onClickClose : () => {}}
className={'modal-container'}
slots={{backdrop: BackdropUnstyled}}>
<div role={'dialog'}>
{showSpinner && <div/>}
<div>
{showSpinner && <Spinner/>}
{children}
</div>
</div>
</ModalUnstyled>
}
interface BlurOverlayProps extends PropsWithOptionalChildren {
classes?: string | string[],
onClick?: () => void,
}
export const BlurOverlay = ({
children,
classes,
onClick,
}: BlurOverlayProps) => {
const [domElementForBlur, setDomElementForBlur] = useState<HTMLElement | null>(null)
useEffect(() => {
const elementToApplyBlurTo = document.getElementById('modal-container-anchor')
if (elementToApplyBlurTo) {
elementToApplyBlurTo!.setAttribute('style', 'backdrop-filter: url(#svgBlur); backdrop-filter: blur(5px); width: 100%; height: 100%; position: absolute; top: 0; left: 0')
setDomElementForBlur(elementToApplyBlurTo)
}
return () => {
if (elementToApplyBlurTo) elementToApplyBlurTo.setAttribute('style', '')
}
}, [])
const _onClick = () => {
if (domElementForBlur) domElementForBlur.setAttribute('style', '')
if (onClick) onClick()
}
return <div
className={clsx('blur-overlay-container', classes)}
onClick={_onClick}>
{children}
</div>
}
I thought by making the execution of onClickClose
conditional, like so !showSpinner ? onClickClose : () => {}
I would prevent the Backdrop from closing, but there seems to be something happening with the <ModalUnstyled />
which I do no understand.