Skip to content

Instantly share code, notes, and snippets.

@andrei-cacio
Created March 3, 2019 10:43
Show Gist options
  • Save andrei-cacio/93379ee01b19c0a16391a74297d907ec to your computer and use it in GitHub Desktop.
Save andrei-cacio/93379ee01b19c0a16391a74297d907ec 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.ref = React.createRef();
}
handleClick = e => {
const isOutside = !this.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.cloneElement(element, { ref: this.ref });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment