-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathclick-outside.js
72 lines (60 loc) · 1.7 KB
/
click-outside.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Component } from 'react';
import PropTypes from 'prop-types';
function isInDOM(obj) {
return Boolean(obj.closest('body'));
}
function hasParent(element, root) {
return root.contains(element) && isInDOM(element);
}
export default class ClickOutside extends Component {
static propTypes = {
active: PropTypes.bool,
onClick: PropTypes.func,
render: PropTypes.func
};
static defaultProps = {
active: true
};
constructor(props) {
super(props);
this.handleRef = this.handleRef.bind(this);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
if (this.props.active) {
document.addEventListener('mousedown', this.handleClick);
document.addEventListener('touchstart', this.handleClick);
}
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (!this.props.active && nextProps.active) {
document.addEventListener('mousedown', this.handleClick);
document.addEventListener('touchstart', this.handleClick);
}
if (this.props.active && !nextProps.active) {
document.removeEventListener('mousedown', this.handleClick);
document.removeEventListener('touchstart', this.handleClick);
}
}
componentWillUnmount() {
if (this.props.active) {
document.removeEventListener('mousedown', this.handleClick);
document.removeEventListener('touchstart', this.handleClick);
}
}
handleRef(element) {
this.element = element;
}
handleClick(event) {
if (!hasParent(event.target, this.element)) {
if (typeof this.props.onClick === 'function') {
this.props.onClick(event);
}
}
}
render() {
return this.props.render({
innerRef: this.handleRef
});
}
}