import * as React from "react"; import { MouseEvent, useEffect, useRef } from "react"; const isClickInsideRectangle = (e: MouseEvent, element: HTMLElement) => { const r = element.getBoundingClientRect(); return ( e.clientX > r.left && e.clientX < r.right && e.clientY > r.top && e.clientY < r.bottom ); }; type Props = { title: string; isOpened: boolean; onClose: () => void; children: React.ReactNode; }; const DialogModal = ({ title, isOpened, onClose, children, }: Props) => { const ref = useRef(null); useEffect(() => { if (isOpened) { ref.current?.showModal(); ref.current?.classList.remove("tw-hidden"); document.body.classList.add("modal-open"); // prevent bg scroll } else { ref.current?.close(); ref.current?.classList.add("tw-hidden"); document.body.classList.remove("modal-open"); } }, [isOpened]); return ( ref.current && !isClickInsideRectangle(e, ref.current) && onClose() } >

{title}

{children}
); }; export default DialogModal;