Created
October 17, 2018 07:14
-
-
Save olecksamdr/c4dbef55db7f732c4c20fec187fa7ea3 to your computer and use it in GitHub Desktop.
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
const withClickOutside = ({ | |
refHandlerName = 'registerRef', | |
clickHandlerName = 'onClick', | |
onClickOutside = () => {}, | |
}) => WrappedComponent => | |
class ClickOutside extends Component { | |
constructor(props) { | |
super(props); | |
this.open = false; | |
this.nodeRef = null; | |
this.onClick = this.onClick.bind(this); | |
this.registerRef = this.registerRef.bind(this); | |
} | |
componentWillUnmount() { | |
body.removeEventListener('click', this.onClick); | |
} | |
onClick(event) { | |
const isInside = this.nodeRef.contains(event.target); | |
const isOpen = this.open; | |
if (!isInside && isOpen) { | |
body.removeEventListener('click', this.onClick); | |
onClickOutside(this.props); | |
this.open = false; | |
} else if (isInside && !isOpen) { | |
body.addEventListener('click', this.onClick); | |
this.open = true; | |
} | |
} | |
registerRef(ref) { | |
this.nodeRef = ref; | |
} | |
render() { | |
const props = { | |
...this.props, | |
[refHandlerName]: this.registerRef, | |
[clickHandlerName]: this.onClick, | |
}; | |
return <WrappedComponent {...props} />; | |
} | |
}; | |
export default withClickOutside; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment