insomnia/app/components/base/Dropdown.js

54 lines
1.1 KiB
JavaScript
Raw Normal View History

2016-03-21 05:47:49 +00:00
import React, {Component, PropTypes} from 'react';
class Dropdown extends Component {
constructor () {
super();
2016-03-22 05:01:58 +00:00
this.state = {
open: false
};
2016-03-21 05:47:49 +00:00
}
2016-03-21 06:36:39 +00:00
2016-03-21 05:47:49 +00:00
componentDidMount () {
// Capture clicks outside the component and close the dropdown
2016-03-21 06:36:39 +00:00
// TODO: Remove this listener when component unmounts
2016-03-22 05:01:58 +00:00
document.addEventListener('click', this._clickEvenCallback.bind(this));
2016-03-21 05:47:49 +00:00
}
2016-03-23 05:26:27 +00:00
componentWillUnmount () {
document.removeEventListener('click', this._clickEvenCallback);
}
2016-03-22 05:01:58 +00:00
_clickEvenCallback (e) {
if (!this.refs.container.contains(e.target)) {
e.preventDefault();
this.setState({open: false});
}
}
_handleClick (e) {
2016-03-21 05:47:49 +00:00
e.preventDefault();
this.setState({open: !this.state.open});
}
render () {
2016-03-22 05:01:58 +00:00
const classes = ['dropdown'];
this.state.open && classes.push('dropdown--open');
this.props.right && classes.push('dropdown--right');
2016-03-21 05:47:49 +00:00
return (
<div ref="container"
2016-03-22 05:01:58 +00:00
className={classes.join(' ')}
onClick={this._handleClick.bind(this)}>
2016-03-21 05:47:49 +00:00
{this.props.children}
</div>
)
}
}
2016-03-21 06:36:39 +00:00
Dropdown.propTypes = {
right: PropTypes.bool
};
2016-03-21 05:47:49 +00:00
export default Dropdown;