Last active
September 6, 2018 13:16
-
-
Save tomfordweb/ccb408f9bd54c604d7eba7a5755a4bd5 to your computer and use it in GitHub Desktop.
Will hide children if clicked outside of the component. Must pass a boolean to show/hide content. Useful for things like search results.
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
'use strict'; | |
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) { | |
this.setState(update(this.state, { | |
visible: {$set: nextProps.visible} | |
})) | |
} | |
componentDidMount() { | |
document.addEventListener('mousedown', this.handleClickOutside); | |
} | |
componentWillUnmount() { | |
document.removeEventListener('mousedown', this.handleClickOutside); | |
} | |
handleClickOutside(e) { | |
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