Skip to content

Instantly share code, notes, and snippets.

@Fenntasy
Created November 16, 2015 15:15
Show Gist options
  • Save Fenntasy/4b38f1c7d8372d7cc876 to your computer and use it in GitHub Desktop.
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
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