Skip to content

Instantly share code, notes, and snippets.

@marciobarrios
Last active July 29, 2018 18:37
Show Gist options
  • Save marciobarrios/0dd212918b22c4b6db7e213a330fd913 to your computer and use it in GitHub Desktop.
Save marciobarrios/0dd212918b22c4b6db7e213a330fd913 to your computer and use it in GitHub Desktop.
To detect a click outside a React component. More info: https://stackoverflow.com/questions/32553158/detect-click-outside-react-component
import ReactDOM from 'react-dom'
// ...
componentDidMount() {
document.addEventListener('click', this.handleClickOutside, true)
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClickOutside, true)
}
handleClickOutside = (event) => {
const domNode = ReactDOM.findDOMNode(this)
if (!domNode || !domNode.contains(event.target)) {
this.setState({ visible: false })
}
}
import React, { Component } from "react";
class SampleComponent extends Component {
state = {
clickedOutside: false
};
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
myRef = React.createRef();
handleClickOutside = e => {
if (!this.myRef.current.contains(e.target)) {
this.setState({ clickedOutside: true });
}
};
handleClickInside = () => this.setState({ clickedOutside: false });
render() {
return (
<button ref={this.myRef} onClick={this.handleClickInside}>
{this.state.clickedOutside ? "Bye!" : "Hello!"}
</button>
);
}
}
export default SampleComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment