Created
January 31, 2019 06:33
-
-
Save adamgajzlerowicz/3c69dd1df55d7b8c0cba9e9b8ffe552b to your computer and use it in GitHub Desktop.
withClickOutside
This file contains hidden or 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 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