Skip to content

Instantly share code, notes, and snippets.

@andrei-cacio
Created March 3, 2019 10:46
Show Gist options
  • Save andrei-cacio/9cccc6f4f6c7c97d96b2043d28e7c1ba to your computer and use it in GitHub Desktop.
Save andrei-cacio/9cccc6f4f6c7c97d96b2043d28e7c1ba to your computer and use it in GitHub Desktop.
ClickOutside
import React, { Component } from 'React';
import PropTypes from 'prop-types';
class ClickOutside extends Component {
static propTypes = {
onClick: PropTypes.func
}
constructor(props) {
super(props);
this.childrenRefs = React.Children.map(this.props.children, () =>
React.createRef()
);
}
handleClick = e => {
const isOutside = this.childrenRefs.every(
ref => !ref.current.contains(e.target)
);
if (isOutside) {
this.props.onClick();
}
};
componentDidMount() {
document.addEventListener("click", this.handleClick);
}
componentWillUnmount() {
document.removeEventListener("click", this.handleClick);
}
render() {
return React.Children.map(this.props.children, (element, idx) => {
return React.cloneElement(element, { ref: this.childrenRefs[idx] });
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment