accounts-frontend/src/components/ui/form/Dropdown.jsx

138 lines
3.4 KiB
React
Raw Normal View History

import React, { PropTypes } from 'react';
2016-05-28 04:44:28 +05:30
import ReactDOM from 'react-dom';
import classNames from 'classnames';
2016-05-30 10:10:59 +05:30
import { colors, COLOR_GREEN } from 'components/ui';
2016-05-28 04:44:28 +05:30
import styles from './dropdown.scss';
2016-06-18 17:43:28 +05:30
import FormInputComponent from './FormInputComponent';
2016-06-18 17:43:28 +05:30
export default class Dropdown extends FormInputComponent {
static displayName = 'Dropdown';
static propTypes = {
label: PropTypes.oneOfType([
PropTypes.shape({
id: PropTypes.string
}),
PropTypes.string
]).isRequired,
2016-06-18 17:43:28 +05:30
items: PropTypes.arrayOf(PropTypes.oneOfType([
PropTypes.string,
PropTypes.shape({
id: PropTypes.string
})
])).isRequired,
block: PropTypes.bool,
2016-05-30 10:10:59 +05:30
color: PropTypes.oneOf(colors)
};
static defaultProps = {
color: COLOR_GREEN
};
2016-05-28 04:44:28 +05:30
state = {
isActive: false,
2016-06-18 17:43:28 +05:30
activeItem: null
2016-05-28 04:44:28 +05:30
};
2016-05-28 04:44:28 +05:30
componentDidMount() {
document.addEventListener('click', this.onBodyClick);
}
componentWillUnmount() {
document.removeEventListener('click', this.onBodyClick);
}
render() {
2016-05-30 10:10:59 +05:30
const { color, block, items } = this.props;
2016-06-18 17:43:28 +05:30
const {isActive} = this.state;
2016-06-18 17:43:28 +05:30
const activeItem = this.getActiveItem();
const label = this.formatMessage(activeItem.label);
return (
2016-06-18 17:43:28 +05:30
<div>
<div className={classNames(styles[color], {
[styles.block]: block,
[styles.opened]: isActive
})} {...this.props} onClick={this.onToggle}>
{label}
<span className={styles.toggleIcon} />
<div className={styles.menu}>
{Object.entries(items).map(([value, label]) => (
<div className={styles.menuItem} key={value} onClick={this.onSelectItem({value, label})}>
{label}
</div>
))}
</div>
2016-05-28 04:44:28 +05:30
</div>
2016-06-18 17:43:28 +05:30
{this.renderError()}
</div>
);
}
2016-05-28 04:44:28 +05:30
toggle() {
this.setState({
isActive: !this.state.isActive
});
}
onSelectItem(item) {
return (event) => {
event.preventDefault();
this.setState({
activeItem: item
});
};
}
2016-06-18 17:43:28 +05:30
getActiveItem() {
const {items} = this.props;
let {activeItem} = this.state;
if (!activeItem) {
activeItem = {
label: this.props.label,
value: ''
};
if (!activeItem.label) {
const firstItem = Object.entries(items)[0];
activeItem = {
label: firstItem[1],
value: firstItem[0]
};
}
}
return activeItem;
}
getValue() {
return this.getActiveItem().value;
}
2016-05-28 04:44:28 +05:30
onToggle = (event) => {
event.preventDefault();
this.toggle();
};
onBodyClick = (event) => {
if (this.state.isActive) {
const el = ReactDOM.findDOMNode(this);
if (!el.contains(event.target) && el !== event.taget) {
event.preventDefault();
this.toggle();
}
}
};
}