Advertisement
magrega

html5 modal logic

May 5th, 2023
871
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { FC, KeyboardEventHandler, MouseEvent, PropsWithChildren, useCallback, useEffect, useRef } from 'react';
  2. import CrossButton from '../../assets/icons/cross.svg';
  3. import './BaseModal.css';
  4.  
  5. interface IBaseModal {
  6.     open: boolean;
  7.     setOpen: (value: boolean) => void;
  8.     title?: string;
  9. }
  10.  
  11. const BaseModal: FC<PropsWithChildren<IBaseModal>> = ({ open, setOpen, title = "share your story in our feed", children }) => {
  12.  
  13.     const modalRef = useRef<HTMLDialogElement>(null);
  14.  
  15.     const closeModal = useCallback(() => {
  16.         setOpen(false);
  17.         modalRef.current?.close();
  18.     }, [setOpen])
  19.  
  20.     const closeOnBackdropClick = (e: MouseEvent) => {
  21.         const rect = (e.target as Element).getBoundingClientRect();
  22.         if (rect.left > e.clientX || rect.right < e.clientX || rect.top > e.clientY || rect.bottom < e.clientY) modalRef.current?.close();
  23.     }
  24.  
  25.     const closeOnEsc = (e: KeyboardEvent<HTMLDialogElement> ) => {
  26.         console.log(typeof e);
  27.        
  28.         if (e.key === 'Escape') closeModal();
  29.     }
  30.  
  31.     useEffect(() => {
  32.         if (open) modalRef.current?.showModal();
  33.         // modalRef.current?.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeModal() })
  34.         console.log('effect');
  35.        
  36.     }, [open]);
  37.  
  38.     return (
  39.         <dialog onClose={closeModal} onKeyDown={closeOnEsc} onClick={(e) => closeOnBackdropClick(e)} ref={modalRef} className='modal-window'>
  40.             <div className="modal-window__top">
  41.                 <h3>{title}</h3>
  42.                 <img onClick={closeModal} src={CrossButton} alt="Close Button" />
  43.             </div>
  44.             {children}
  45.         </dialog>
  46.     )
  47. };
  48.  
  49. export default BaseModal;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement