Skip to content

Instantly share code, notes, and snippets.

@tonyhschu
Created May 12, 2016 22:45
Show Gist options
  • Save tonyhschu/a4bd7d3f4bab036770a38f966c3795a1 to your computer and use it in GitHub Desktop.
Save tonyhschu/a4bd7d3f4bab036770a38f966c3795a1 to your computer and use it in GitHub Desktop.
Closing pop-ups by clicking outside in React
// Making a gist, because I know I'm going to have to find this again...
// Of course, this is a terrible hack. I recommend this only to the desperate (and those who don't want to use mixins.)
componentWillReceiveProps(nextProps) {
if (nextProps.isOpen) {
window.addEventListener('mousedown', this.pageClick, false)
} else {
window.removeEventListener('mousedown', this.pageClick, false)
}
}
componentWillUnmount() {
window.removeEventListener('mousedown', this.pageClick, false)
}
pageClick(e) {
let box = this.refs.popover.getBoundingClientRect()
// Click is outside of the bounding client
let outsizeWidthWise = (e.clientX > box.right || e.clientX < box.left)
let outsizeHeightWise = (e.clientY > box.bottom || e.clientY < box.top)
if (outsizeWidthWise || outsizeHeightWise) {
this.props.functionThatClosesThePopOver()
}
}
render() {
return (
<div ref="popover">
This is the popover.
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment