Last active
July 29, 2018 18:37
-
-
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
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 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 }) | |
} | |
} |
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 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