Skip to content

Instantly share code, notes, and snippets.

@henrikhaugboelle
Last active November 2, 2017 14:54
Show Gist options
  • Save henrikhaugboelle/abae622b05565d04bb76962f08fbad68 to your computer and use it in GitHub Desktop.
Save henrikhaugboelle/abae622b05565d04bb76962f08fbad68 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class CatchGlobalClick extends Component {
static propTypes = {
onClick: PropTypes.func,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
])
}
componentWillMount() {
document.addEventListener('click', this.handleGlobalClick, false);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleGlobalClick, false);
}
handleGlobalClick = (event) => {
if (this.element && !this.element.contains(event.target)) {
if (this.props.onClick) {
this.props.onClick();
}
}
}
render() {
return (
<div ref={(e) => { this.element = e; }}>
{this.props.children}
</div>
);
}
}
export default CatchGlobalClick;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment