All files / javascripts/explorev2/components SelectField.jsx

91.67% Statements 22/24
58.33% Branches 7/12
60% Functions 3/5
95.24% Lines 20/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 731x 1x 1x 1x     1x                     1x           1x         1x   1x     1x     8x 4x   2x 1x 1x       4x                   4x     4x                       1x 1x  
import React, { PropTypes } from 'react';
import ControlLabelWithTooltip from './ControlLabelWithTooltip';
import { slugify } from '../../modules/utils';
import Select, { Creatable } from 'react-select';
 
 
const propTypes = {
  name: PropTypes.string.isRequired,
  choices: PropTypes.array,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  label: PropTypes.string,
  description: PropTypes.string,
  onChange: PropTypes.func,
  multi: PropTypes.bool,
  freeForm: PropTypes.bool,
};
 
const defaultProps = {
  multi: false,
  freeForm: false,
  value: '',
  label: null,
  description: null,
  onChange: () => {},
};
 
export default class SelectField extends React.Component {
  onChange(opt) {
    let optionValue = opt ? opt.value : null;
    // if multi, return options values as an array
    Iif (this.props.multi) {
      optionValue = opt ? opt.map((o) => o.value) : null;
    }
    this.props.onChange(this.props.name, optionValue);
  }
  render() {
    const options = this.props.choices.map((c) => ({ value: c[0], label: c[1] }));
    if (this.props.freeForm) {
      // For FreeFormSelect, insert value into options if not exist
      const values = this.props.choices.map((c) => c[0]);
      Eif (values.indexOf(this.props.value) === -1) {
        options.push({ value: this.props.value, label: this.props.value });
      }
    }
 
    const selectProps = {
      multi: this.props.multi,
      name: `select-${this.props.name}`,
      placeholder: `Select (${this.props.choices.length})`,
      options,
      value: this.props.value,
      autosize: false,
      onChange: this.onChange.bind(this),
    };
    //  Tab, comma or Enter will trigger a new option created for FreeFormSelect
    const selectWrap = this.props.freeForm ?
      (<Creatable {...selectProps} />) : (<Select {...selectProps} />);
 
    return (
      <div id={`formControlsSelect-${slugify(this.props.label)}`}>
        <ControlLabelWithTooltip
          label={this.props.label}
          description={this.props.description}
        />
        {selectWrap}
      </div>
    );
  }
}
 
SelectField.propTypes = propTypes;
SelectField.defaultProps = defaultProps;