-
Notifications
You must be signed in to change notification settings - Fork 1
/
Modal.js
54 lines (44 loc) · 1.4 KB
/
Modal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import './Modal.css';
import Close from '../icons/Close';
function Modal(props) {
const { children, onClose } = props;
const modalContentRef = useRef();
useEffect(() => {
const handleKeyUp = event => {
if (event.key === 'Escape') {
onClose();
}
};
const handleMouseDown = event => {
if (!modalContentRef.current.contains(event.target)) {
onClose();
}
};
window.addEventListener('mousedown', handleMouseDown);
window.addEventListener('keyup', handleKeyUp);
return () => {
window.removeEventListener('mousedown', handleMouseDown);
window.removeEventListener('keyup', handleKeyUp);
};
}, [onClose]);
return ReactDOM.createPortal(
<div className="modal">
<div className="modal-overlay" />
<div className="modal-content" ref={modalContentRef}>
<button className="modal-close" onClick={onClose}>
<Close />
</button>
{children}
</div>
</div>,
document.getElementsByTagName('body')[0]
);
}
Modal.propTypes = {
children: PropTypes.node,
onClose: PropTypes.func
};
export default Modal;