Skip to content

Instantly share code, notes, and snippets.

@slorber
Created February 23, 2016 10:26
Show Gist options
  • Save slorber/d0a638b9e54bd7dcc564 to your computer and use it in GitHub Desktop.
Save slorber/d0a638b9e54bd7dcc564 to your computer and use it in GitHub Desktop.
WithOutsideClickListener
'use strict';
var React = require("react");
var ReactDOM = require("react-dom");
var WithOutsideClickListener = React.createClass({
propTypes: {
children: React.PropTypes.node.isRequired,
onOutsideClick: React.PropTypes.func.isRequired,
// Sometimes some outside clicks have to be bypassed and not trigger the "onOutsideClick" function
shouldBypass: React.PropTypes.func
},
componentDidMount: function() {
document.addEventListener('mousedown', this.handleMouseClick);
document.addEventListener('touchstart', this.handleMouseClick);
},
componentWillUnmount: function() {
document.removeEventListener('mousedown', this.handleMouseClick);
document.removeEventListener('touchstart', this.handleMouseClick);
},
handleMouseClick: function(e) {
if ( this.props.shouldBypass && this.props.shouldBypass(e.target) ) {
return;
}
var isInsideClick = isNodeInRoot( e.target, ReactDOM.findDOMNode(this) );
if ( !isInsideClick) {
this.props.onOutsideClick(e);
}
},
render: function() {
return React.Children.only(this.props.children);
}
});
module.exports = WithOutsideClickListener;
function isNodeInRoot(node, root) {
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}
return false;
}
@slorber
Copy link
Author

slorber commented Feb 23, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment