Created
March 3, 2019 10:43
-
-
Save andrei-cacio/93379ee01b19c0a16391a74297d907ec to your computer and use it in GitHub Desktop.
ClickOutside
This file contains 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, { 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