Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adamgajzlerowicz/3c69dd1df55d7b8c0cba9e9b8ffe552b to your computer and use it in GitHub Desktop.
Save adamgajzlerowicz/3c69dd1df55d7b8c0cba9e9b8ffe552b to your computer and use it in GitHub Desktop.
withClickOutside
import React from 'react'
const withClickOutside = Component => {
class Wrapped extends React.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)
}
setWrapperRef(node) {
this.wrapperRef = node
}
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
const { onClickOutside } = this.props
onClickOutside && onClickOutside()
}
}
render() {
return (
<div ref={this.setWrapperRef} style={{ display: 'inline-block' }}>
<Component {...this.props} />
</div>
)
}
}
return Wrapped
}
export default withClickOutside
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment