-
Notifications
You must be signed in to change notification settings - Fork 41
/
index.js
60 lines (48 loc) · 1.55 KB
/
index.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
// @flow
const hoistNonReactStatic = require('hoist-non-react-statics');
const React = require('react');
const ReactDOM = require('react-dom');
function enhanceWithClickOutside(Component: React.ComponentType<*>) {
const componentName = Component.displayName || Component.name;
class EnhancedComponent extends React.Component<*> {
__domNode: *;
__wrappedInstance: ?React.Component<*>;
handleClickOutside: (e: Event) => void;
constructor(props) {
super(props);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener('click', this.handleClickOutside, true);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClickOutside, true);
}
handleClickOutside(e) {
const domNode = this.__domNode;
if (
(!domNode || !domNode.contains(e.target)) &&
this.__wrappedInstance &&
typeof this.__wrappedInstance.handleClickOutside === 'function'
) {
this.__wrappedInstance.handleClickOutside(e);
}
}
render() {
const { wrappedRef, ...rest } = this.props;
return (
<Component
{...rest}
ref={c => {
this.__wrappedInstance = c;
this.__domNode = ReactDOM.findDOMNode(c);
wrappedRef && wrappedRef(c);
}}
/>
);
}
}
EnhancedComponent.displayName = `clickOutside(${componentName})`;
return hoistNonReactStatic(EnhancedComponent, Component);
}
module.exports = enhanceWithClickOutside;