Skip to content

Instantly share code, notes, and snippets.

@tomfordweb
Created October 31, 2018 18:49
Show Gist options
  • Save tomfordweb/d2e1095d5df551d483da55f59ff61998 to your computer and use it in GitHub Desktop.
Save tomfordweb/d2e1095d5df551d483da55f59ff61998 to your computer and use it in GitHub Desktop.
Hide if clicked outside - React Component
import React from 'react';
import update from 'immutability-helper';
export default class HideIfClickedOutside extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: this.props.visible || false
}
this.handleClickOutside = this.handleClickOutside.bind(this);
this.setWrapperRef = this.setWrapperRef.bind(this);
}
setWrapperRef(node) {
this.wrapperRef = node;
}
componentWillReceiveProps(nextProps) {
// if(this.state.visible !== nextProps.visible) {
this.setState(update(this.state, {
visible: {$set: nextProps.visible}
}))
// }
}
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
this.setState(update(this.state, {
visible: {$set: false}
}))
if(this.props.callback)
this.props.callback();
}
}
render() {
return this.state.visible
? <div ref={this.setWrapperRef}>{this.props.children}</div>
: <span />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment