/
Percival
/
react_final_project
Обзор
Документация
Войти
/
Percival
/
react_final_project
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/shared/ui/Modal/Modal.tsx
57 строк
2 KB
Rituparn
Added code
23 ноя 2025, 19:02
23 ноя 2025, 19:02
2aec7c7
Код
Авторство
О чём код?
import { useEffect, useRef } from 'react'; import { createPortal } from 'react-dom'; import s from './Modal.module.css'; interface ModalProps { isOpen: boolean; onClose: () => void; children: React.ReactNode; } export const Modal = ({ isOpen, onClose, children }: ModalProps) => { const closeButtonRef = useRef<HTMLButtonElement>(null); const previousFocusRef = useRef<HTMLElement | null>(null); useEffect(() => { const handleEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') { onClose(); } }; if (isOpen) { previousFocusRef.current = document.activeElement as HTMLElement; document.addEventListener('keydown', handleEsc); document.body.style.overflow = 'hidden'; setTimeout(() => { closeButtonRef.current?.focus(); }, 0); } else { previousFocusRef.current?.focus(); } return () => { document.removeEventListener('keydown', handleEsc); document.body.style.overflow = 'unset'; if (isOpen) { previousFocusRef.current?.focus(); } }; }, [isOpen, onClose]); if (!isOpen) return null; const root = document.getElementById('modal-root'); if (!root) return null; return createPortal( <div className={s.overlay} onClick={onClose}> <div className={s.content} onClick={(e) => e.stopPropagation()} tabIndex={-1} role="dialog" aria-modal="true"> <button className={s.closeButton} onClick={onClose} aria-label="Close modal" ref={closeButtonRef}>×</button> {children} </div> </div>, root ); };