import React, { useEffect } from 'react'; import ReactDOM from 'react-dom'; import './style.scss'; interface ModalProps { isOpen: boolean; onClose: () => void; children: React.ReactNode; className?: string; contentClassName?: string; showCloseButton?: boolean; } // Get or create modal root immediately const getModalRoot = () => { let root = document.getElementById('modal-root'); if (!root) { root = document.createElement('div'); root.id = 'modal-root'; document.body.appendChild(root); } return root; }; export const Modal: React.FC = ({ isOpen, onClose, children, className = '', contentClassName = '', showCloseButton = true }) => { useEffect(() => { const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape') { onClose(); } }; if (isOpen) { document.addEventListener('keydown', handleEscape); document.body.style.overflow = 'hidden'; // Force a reflow to ensure the modal appears immediately getModalRoot().offsetHeight; } return () => { document.removeEventListener('keydown', handleEscape); document.body.style.overflow = 'unset'; }; }, [isOpen, onClose]); if (!isOpen) return null; const modalContent = (
e.stopPropagation()}> {showCloseButton && ( )} {children}
); // Use portal to render at document body level return ReactDOM.createPortal(modalContent, getModalRoot()); };