Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.