insomnia/app/components/base/Dropdown.js

52 lines
1.2 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) {
2016-03-24 05:26:04 +00:00
if (this.refs.container && !this.refs.container.contains(e.target)) {
2016-03-22 05:01:58 +00:00
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-04-04 07:15:30 +00:00
const classes = ['dropdown'].concat(this.props.className || []);
2016-03-22 05:01:58 +00:00
this.state.open && classes.push('dropdown--open');
this.props.right && classes.push('dropdown--right');
2016-03-21 05:47:49 +00:00
return (
2016-04-03 22:54:39 +00:00
<div ref="container" 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;