Skip to content

Instantly share code, notes, and snippets.

@zerkalica
Created October 7, 2015 09:41
Show Gist options
  • Save zerkalica/f32570f211e63f1844ba to your computer and use it in GitHub Desktop.
Save zerkalica/f32570f211e63f1844ba to your computer and use it in GitHub Desktop.
import {Func} from 'tcomb'
import {ReactNode, propTypes} from 'tcomb-react'
import React from 'react'
import events from 'add-event-listener'
const findDOMNode = React.findDOMNode
export default class OutsideClick extends React.Component {
_localNode = null
static propTypes = propTypes({
onClick: Func,
children: ReactNode
})
constructor(props, context) {
super(props, context)
this._clickHandler = ::this._clickHandler
}
_clickHandler(event) {
const {onClick} = this.props
let source = event.target
let found = false
event.stopPropagation()
while (!found && source.parentNode) {
found = source === this._localNode
source = source.parentNode
}
if (!found) {
onClick(event)
}
}
componentDidMount() {
this._localNode = findDOMNode(this)
events.addEventListener(document, 'mousedown', this._clickHandler)
events.addEventListener(document, 'touchstart', this._clickHandler)
}
componentWillUnmount() {
events.removeEventListener(document, 'mousedown', this._clickHandler)
events.removeEventListener(document, 'touchstart', this._clickHandler)
this._localNode = null
}
render() {
const {children} = this.props
return (
<div>
{children}
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment