Created
October 31, 2018 18:49
-
-
Save tomfordweb/d2e1095d5df551d483da55f59ff61998 to your computer and use it in GitHub Desktop.
Hide if clicked outside - React Component
This file contains hidden or 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 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