Skip to content

Commit

Permalink
Add background click/touch to close modal
Browse files Browse the repository at this point in the history
  • Loading branch information
baymac committed Jul 11, 2021
1 parent 38f5a3a commit 329dee5
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions components/Modal/Modal.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { UilTimesCircle } from '@iconscout/react-unicons';
import FocusTrap from 'focus-trap-react';
import React, {
KeyboardEvent,
ReactChildren,
useEffect,
useRef,
useState,
KeyboardEvent,
} from 'react';
import ReactDOM from 'react-dom';
import styles from './modal.module.css';
import { UilTimesCircle } from '@iconscout/react-unicons';
import usePreventScroll from '../../hooks/usePreventScroll';
// import * as focusTrap from 'focus-trap'; // ESM
import FocusTrap from 'focus-trap-react';
import styles from './modal.module.css';

export interface IModalProps {
open: boolean;
Expand All @@ -19,6 +19,7 @@ export interface IModalProps {

function Modal(props: IModalProps) {
const { open, handleClose, children } = props;
usePreventScroll(open);

const [isBrowser, setIsBrowser] = useState(false);

Expand Down Expand Up @@ -47,7 +48,13 @@ function Modal(props: IModalProps) {
handleClose();
};

usePreventScroll(open);
const modalBgRef = useRef();

const handleBgClick = (e) => {
if (modalBgRef.current === e.target) {
handleCloseClick(e);
}
};

const modalContent = open ? (
<div
Expand All @@ -65,6 +72,9 @@ function Modal(props: IModalProps) {
className={styles.modal__container}
tabIndex={-1}
role="none presentation"
ref={modalBgRef}
/* Works both for mouse click and touch events */
onMouseDown={handleBgClick}
>
{/* To prevent any content being focused on modal open */}
<div tabIndex={0}></div>
Expand Down

1 comment on commit 329dee5

@vercel
Copy link

@vercel vercel bot commented on 329dee5 Jul 11, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.