Created
February 23, 2016 10:26
-
-
Save slorber/d0a638b9e54bd7dcc564 to your computer and use it in GitHub Desktop.
WithOutsideClickListener
This file contains 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
'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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Initially inspired from https://github.com/tajo/react-portal/blob/master/lib/portal.js