-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
62 lines (52 loc) · 1.53 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
61
62
import React, { Component } from "react"
import PropTypes from "prop-types"
export default class EscapeOutside extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
onEscapeOutside: PropTypes.func.isRequired,
mouseEvent: PropTypes.string,
touchEvent: PropTypes.string,
}
static defaultProps = {
mouseEvent: "click",
touchEvent: "touchend",
}
constructor() {
super()
this.onEscape = this.onEscape.bind(this)
this.onClick = this.onClick.bind(this)
this.getRef = this.getRef.bind(this)
}
componentDidMount() {
document.addEventListener("keydown", this.onEscape)
document.addEventListener(this.props.mouseEvent, this.onClick, true)
document.addEventListener(this.props.touchEvent, this.onClick, true)
}
componentWillUnmount() {
document.removeEventListener("keydown", this.onEscape)
document.removeEventListener(this.props.mouseEvent, this.onClick, true)
document.removeEventListener(this.props.touchEvent, this.onClick, true)
}
onEscape(e) {
if (e.keyCode === 27) this.props.onEscapeOutside()
}
onClick(e) {
if (this.ref && !this.ref.contains(e.target)) this.props.onEscapeOutside(e)
}
getRef(ref) {
this.ref = ref
}
render() {
const props = Object.assign({}, this.props)
const { children } = props
delete props.onEscapeOutside
delete props.children
delete props.mouseEvent
delete props.touchEvent
return (
<div ref={this.getRef} {...props}>
{children}
</div>
)
}
}