Created
March 3, 2019 10:46
-
-
Save andrei-cacio/9cccc6f4f6c7c97d96b2043d28e7c1ba 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.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