Skip to content

Instantly share code, notes, and snippets.

@olecksamdr
Created October 17, 2018 07:14
Show Gist options
  • Save olecksamdr/c4dbef55db7f732c4c20fec187fa7ea3 to your computer and use it in GitHub Desktop.
Save olecksamdr/c4dbef55db7f732c4c20fec187fa7ea3 to your computer and use it in GitHub Desktop.
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