Skip to content

Instantly share code, notes, and snippets.

@markmur
Last active February 16, 2020 14:46
Show Gist options
  • Save markmur/0f95eea3be74dad01642a1f79b37c07c to your computer and use it in GitHub Desktop.
Save markmur/0f95eea3be74dad01642a1f79b37c07c to your computer and use it in GitHub Desktop.
Handle Click Outside
const handleClickOutside = (Component, useCapture = true) => {
return class extends React.Component {
// Create a reference to the component instance
instance = React.createRef()
// Create a reference to the component DOM element (forwardedRef)
node = React.createRef()
componentDidMount() {
document.addEventListener('click', this.handleClick, useCapture)
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick, useCapture)
}
handleClick = event => {
if (!this.instance || ! this.instance.current) return
if (!this.node.current.contains(event.target)) {
if (typeof this.instance.current.onClickOutside === 'function') {
this.instance.current.onClickOutside(event)
}
}
}
render() {
return (
<Component
ref={this.instance}
forwardedRef={this.node}
{...this.props}
/>
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment