import './Modal.css'; import * as React from 'react'; import { useEffect, useRef } from 'react'; import { createPortal } from 'react-dom'; function PortalImpl({ onClose, children, title, closeOnClickOutside, }: { children: JSX.Element | string | (JSX.Element | string)[]; closeOnClickOutside: boolean; onClose: () => void; title: string; }) { const modalRef = useRef(); useEffect(() => { if (modalRef.current !== null) { modalRef.current.focus(); } }, []); useEffect(() => { let modalOverlayElement = null; const handler = event => { if (event.keyCode === 27) { onClose(); } }; const clickOutsideHandler = (event: MouseEvent) => { const target = event.target; if (modalRef.current !== null && !modalRef.current.contains(target as Node) && closeOnClickOutside) { onClose(); } }; if (modalRef.current !== null) { modalOverlayElement = modalRef.current?.parentElement; if (modalOverlayElement !== null) { modalOverlayElement?.addEventListener('click', clickOutsideHandler); } } window.addEventListener('keydown', handler); return () => { window.removeEventListener('keydown', handler); if (modalOverlayElement !== null) { modalOverlayElement?.removeEventListener('click', clickOutsideHandler); } }; }, [closeOnClickOutside, onClose]); return (

{title}

{children}
); } export default function Modal({ onClose, children, title, closeOnClickOutside = false, }: { children: JSX.Element | string | (JSX.Element | string)[]; closeOnClickOutside?: boolean; onClose: () => void; title: string; }): JSX.Element { return createPortal( {children} , document.body ); }