Last active
November 2, 2017 14:54
-
-
Save henrikhaugboelle/abae622b05565d04bb76962f08fbad68 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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