import "./Modal.css"; import React, { useEffect, useState } from "react"; import { createPortal } from "react-dom"; import { KEYS } from "../keys"; export function Modal(props: { children: React.ReactNode; maxWidth?: number; onCloseRequest(): void; labelledBy: string; }) { const modalRoot = useBodyRoot(); const handleKeydown = (e: React.KeyboardEvent) => { if (e.key === KEYS.ESCAPE) { e.nativeEvent.stopImmediatePropagation(); props.onCloseRequest(); } }; return createPortal(
{props.children}
, modalRoot, ); } function useBodyRoot() { function createDiv() { const div = document.createElement("div"); document.body.appendChild(div); return div; } const [div] = useState(createDiv); useEffect(() => { return () => { document.body.removeChild(div); }; }, [div]); return div; }