Skip to content

Instantly share code, notes, and snippets.

@hudochenkov
Forked from alexbeletsky/1_outside.js
Last active August 4, 2016 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hudochenkov/fb435937ad23070288fcbee49868752b to your computer and use it in GitHub Desktop.
Save hudochenkov/fb435937ad23070288fcbee49868752b to your computer and use it in GitHub Desktop.
class DropdownContainer extends Component {
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 });
}
render() {
return (
<OutsideClick tag="ul" className="list-unstyled navbar-right" onClick={this.handleOutsideClick}>
<Dropdown
visible={this.state.visible}
onToggle={this.handleToggle}
/>
</OutsideClick>
);
}
}
export default DropdownContainer;
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
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick, true);
}
componentDidMount() {
document.addEventListener('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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment