Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { FC, KeyboardEventHandler, MouseEvent, PropsWithChildren, useCallback, useEffect, useRef } from 'react';
- import CrossButton from '../../assets/icons/cross.svg';
- import './BaseModal.css';
- interface IBaseModal {
- open: boolean;
- setOpen: (value: boolean) => void;
- title?: string;
- }
- const BaseModal: FC<PropsWithChildren<IBaseModal>> = ({ open, setOpen, title = "share your story in our feed", children }) => {
- const modalRef = useRef<HTMLDialogElement>(null);
- const closeModal = useCallback(() => {
- setOpen(false);
- modalRef.current?.close();
- }, [setOpen])
- const closeOnBackdropClick = (e: MouseEvent) => {
- const rect = (e.target as Element).getBoundingClientRect();
- if (rect.left > e.clientX || rect.right < e.clientX || rect.top > e.clientY || rect.bottom < e.clientY) modalRef.current?.close();
- }
- const closeOnEsc = (e: KeyboardEvent<HTMLDialogElement> ) => {
- console.log(typeof e);
- if (e.key === 'Escape') closeModal();
- }
- useEffect(() => {
- if (open) modalRef.current?.showModal();
- // modalRef.current?.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeModal() })
- console.log('effect');
- }, [open]);
- return (
- <dialog onClose={closeModal} onKeyDown={closeOnEsc} onClick={(e) => closeOnBackdropClick(e)} ref={modalRef} className='modal-window'>
- <div className="modal-window__top">
- <h3>{title}</h3>
- <img onClick={closeModal} src={CrossButton} alt="Close Button" />
- </div>
- {children}
- </dialog>
- )
- };
- export default BaseModal;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement