Created
August 23, 2017 09:20
-
-
Save fazlurr/9b418b09ae6b78701c503c9875239569 to your computer and use it in GitHub Desktop.
React Detect Click Outside Component - https://stackoverflow.com/a/42234988
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
/** | |
* Component that alerts if you click outside of it | |
*/ | |
class OutsideAlerter extends Component { | |
constructor(props) { | |
super(props); | |
this.setWrapperRef = this.setWrapperRef.bind(this); | |
this.handleClickOutside = this.handleClickOutside.bind(this); | |
} | |
componentDidMount() { | |
document.addEventListener('mousedown', this.handleClickOutside); | |
} | |
componentWillUnmount() { | |
document.removeEventListener('mousedown', this.handleClickOutside); | |
} | |
/** | |
* Set the wrapper ref | |
*/ | |
setWrapperRef(node) { | |
this.wrapperRef = node; | |
} | |
/** | |
* Alert if clicked on outside of element | |
*/ | |
handleClickOutside(event) { | |
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) { | |
alert('You clicked outside of me!'); | |
} | |
} | |
render() { | |
return ( | |
<div ref={this.setWrapperRef}> | |
{this.props.children} | |
</div> | |
); | |
} | |
} | |
OutsideAlerter.propTypes = { | |
children: React.PropTypes.element.isRequired | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment