2018-03-01 17:53:29 +00:00
|
|
|
import React from 'react';
|
|
|
|
import Select, { ReactSelectProps } from 'react-select';
|
2017-05-23 23:06:01 +00:00
|
|
|
|
2018-03-01 17:53:29 +00:00
|
|
|
interface Props extends ReactSelectProps {
|
|
|
|
className?: string;
|
|
|
|
options: any;
|
|
|
|
onChange: any;
|
2017-09-25 02:06:28 +00:00
|
|
|
}
|
2017-07-04 01:25:01 +00:00
|
|
|
|
2018-03-01 17:53:29 +00:00
|
|
|
export default class Dropdown extends React.Component<Props> {
|
2018-01-03 03:18:10 +00:00
|
|
|
public state = {
|
2018-03-01 17:53:29 +00:00
|
|
|
selectedOption: { value: '', label: '' },
|
|
|
|
hasBlurred: false
|
|
|
|
};
|
|
|
|
|
|
|
|
public handleChange = selectedOption => {
|
|
|
|
this.setState({ selectedOption });
|
2018-01-03 03:18:10 +00:00
|
|
|
};
|
|
|
|
|
2018-03-01 17:53:29 +00:00
|
|
|
public formatOptions = options => {
|
|
|
|
if (typeof options[0] === 'object') {
|
|
|
|
return options;
|
|
|
|
}
|
|
|
|
const formatted = options.map(opt => {
|
|
|
|
return { value: opt, label: opt };
|
|
|
|
});
|
|
|
|
return formatted;
|
|
|
|
};
|
2017-05-23 23:06:01 +00:00
|
|
|
|
2017-09-25 02:06:28 +00:00
|
|
|
public render() {
|
2018-03-01 17:53:29 +00:00
|
|
|
const { onChange } = this.props;
|
|
|
|
const { selectedOption } = this.state;
|
|
|
|
const value = selectedOption && selectedOption.value;
|
|
|
|
const options = this.formatOptions(this.props.options);
|
2017-05-23 23:06:01 +00:00
|
|
|
|
2017-07-02 05:49:06 +00:00
|
|
|
return (
|
2018-03-01 17:53:29 +00:00
|
|
|
<Select
|
|
|
|
// use ref to prevent <label /> from stealing focus when used inline with an input
|
|
|
|
ref={el => {
|
|
|
|
if (!!el && !!(el as any).control) {
|
|
|
|
(el as any).control.addEventListener('click', e => {
|
|
|
|
e.preventDefault();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}}
|
|
|
|
className={`${this.props.className} ${this.state.hasBlurred ? 'has-blurred' : ''}`}
|
|
|
|
value={value}
|
|
|
|
onChange={obj => {
|
|
|
|
this.handleChange(obj);
|
|
|
|
onChange();
|
|
|
|
}}
|
|
|
|
{...this.props}
|
|
|
|
onBlur={e => {
|
|
|
|
this.setState({ hasBlurred: true });
|
|
|
|
if (this.props && this.props.onBlur) {
|
|
|
|
this.props.onBlur(e);
|
|
|
|
}
|
|
|
|
}}
|
|
|
|
options={options}
|
2017-10-02 22:36:59 +00:00
|
|
|
/>
|
2017-07-02 05:49:06 +00:00
|
|
|
);
|
|
|
|
}
|
2017-05-23 23:06:01 +00:00
|
|
|
}
|