Last active
February 16, 2020 14:46
-
-
Save markmur/0f95eea3be74dad01642a1f79b37c07c to your computer and use it in GitHub Desktop.
Handle Click Outside
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
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