Skip to content

Instantly share code, notes, and snippets.

@tomfordweb
Last active September 6, 2018 13:16
Show Gist options
  • Save tomfordweb/ccb408f9bd54c604d7eba7a5755a4bd5 to your computer and use it in GitHub Desktop.
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.
'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