Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import React, { Component, PropTypes } from 'react';
class OutsideClick extends Component {
static propTypes = {
children: PropTypes.any,
onClick: PropTypes.func.isRequired,
id: PropTypes.string,
tag: PropTypes.string,
className: PropTypes.string
}
componentDidMount() {
document.addEventListener('click', this.handleClick, true);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick, true);
}
handleClick = (e) => {
const outside = this.refs.outside;
// clicked outside
if (!outside.contains(e.target)) {
this.props.onClick(e, this.props.id);
}
}
render() {
return React.createElement(
this.props.tag || 'div',
{ className: this.props.className, ref: 'outside' },
this.props.children
);
}
}
export default OutsideClick;
class DropdownContainer extends Component {
static propTypes = {
user: PropTypes.object.isRequired,
onLogout: PropTypes.func.isRequired
};
constructor(...args) {
super(...args);
this.state = {
visible: false
};
}
handleToggle = (e) => {
e.preventDefault();
this.setState({ visible: !this.state.visible });
}
handleOutsideClick = (e) => {
e.preventDefault();
this.setState({ visible: false });
}
handleLogout = (e) => {
e.preventDefault();
this.props.onLogout();
}
render() {
const {
user
} = this.props;
return (
<OutsideClick tag="ul" className="list-unstyled navbar-right" onClick={this.handleOutsideClick}>
<Dropdown
user={user}
visible={this.state.visible}
onLogout={this.handleLogout}
onToggle={this.handleToggle}
/>
</OutsideClick>
);
}
}
export default DropdownContainer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment