/
index.jsx
53 lines (45 loc) · 1.15 KB
/
index.jsx
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
import React from 'react';
import PropTypes from 'prop-types';
import './OutsideClickHandler.scss';
const propTypes = {
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.arrayOf(PropTypes.element),
]).isRequired,
onOutSideClick: PropTypes.func,
};
const defaultProps = {
onOutSideClick() {},
};
class OutsideClickHandler extends React.Component {
constructor(props) {
super(props);
this.handleOutSideClick = this.handleOutSideClick.bind(this);
}
componentDidMount() {
document.addEventListener('click', this.handleOutSideClick);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleOutSideClick);
}
handleOutSideClick(e) {
const { onOutSideClick } = this.props;
if (!this.outsideRef.contains(e.target)) {
onOutSideClick();
}
}
render() {
const { children } = this.props;
return (
<div
className="OutsideClickHandler"
ref={(ref) => { this.outsideRef = ref; }}
>
{children}
</div>
);
}
}
OutsideClickHandler.propTypes = propTypes;
OutsideClickHandler.defaultProps = defaultProps;
export default OutsideClickHandler;