Created
November 16, 2015 15:15
-
-
Save Fenntasy/4b38f1c7d8372d7cc876 to your computer and use it in GitHub Desktop.
Mixin to check if someone has clicked outside of the current react element
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
import { findDOMNode } from 'react-dom' | |
const OnClickOutside = { | |
componentDidMount: function() { | |
if(!this.handleClickOutside) { | |
throw new Error('missing handleClickOutside(event) function in Component ' + this.displayName) | |
} | |
document.addEventListener("click", this.listenForClickOutside) | |
}, | |
listenForClickOutside: function(e) { | |
if (!this.isMounted()) { | |
return; | |
} | |
// Like shouldComponentUpdate but for checking outside click | |
// Way of saying "don't bother to check rigth now, not usefull" | |
if (this["shouldCheckForClickOutside"] && !this.shouldCheckForClickOutside()) { | |
return; | |
} | |
let source = e.target | |
if (source === findDOMNode(this)) { | |
return; | |
} | |
if (source.parentNode === null) { | |
const container = findDOMNode(this).getBoundingClientRect() | |
const mouseX = e.clientX | |
const mouseY = e.clientY | |
if (mouseX >= container.left && mouseX <= container.right | |
&& mouseY >= container.top && mouseY <= container.bottom) { | |
return; | |
} | |
} | |
let found = false | |
// make sure event is not from something "owned" by this component: | |
while(source.parentNode) { | |
source = source.parentNode | |
found = (source === findDOMNode(this)) | |
if(found) return; | |
} | |
e.insideElement = findDOMNode(this) | |
this.handleClickOutside(e) | |
}, | |
componentWillUnmount: function() { | |
document.removeEventListener("click", this.listenForClickOutside) | |
} | |
}; | |
export default OnClickOutside; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment