| 1 |
import React, { Component } from 'react'; |
| 2 |
import Select from 'react-select'; |
| 3 |
import CreatableSelect from 'react-select/creatable'; |
| 4 |
|
| 5 |
export default class FieldDropdown extends Component { |
| 6 |
shouldComponentUpdate(nextProps) { |
| 7 |
return JSON.stringify(this.props.options) !== JSON.stringify(nextProps.options) || this.props.value !== nextProps.value || this.props.isDisabled !== nextProps.isDisabled; |
| 8 |
} |
| 9 |
|
| 10 |
render() { |
| 11 |
const isMulti = this.props.isMulti ? this.props.isMulti : false; |
| 12 |
let selectedOption = false; |
| 13 |
|
| 14 |
if ( this.props.options ) { |
| 15 |
const allOptions = this.props.options.reduce((acc, cur) => { |
| 16 |
if ( cur.hasOwnProperty('options') ) { |
| 17 |
acc = acc.concat( cur.options ); |
| 18 |
} else { |
| 19 |
acc.push(cur); |
| 20 |
} |
| 21 |
|
| 22 |
return acc; |
| 23 |
}, []); |
| 24 |
|
| 25 |
if ( isMulti ) { |
| 26 |
selectedOption = allOptions.filter(({value}) => this.props.value.includes(value)) |
| 27 |
} else { |
| 28 |
selectedOption = allOptions.find((option) => option.value === this.props.value); |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
const customProps = this.props.custom ? this.props.custom : {}; |
| 33 |
const SelectElem = this.props.creatable ? CreatableSelect : Select; |
| 34 |
|
| 35 |
return ( |
| 36 |
<SelectElem |
| 37 |
isMulti={ isMulti } |
| 38 |
isDisabled={ this.props.isDisabled } |
| 39 |
options={this.props.options} |
| 40 |
value={selectedOption} |
| 41 |
placeholder={this.props.placeholder} |
| 42 |
onChange={(option) => { |
| 43 |
if ( isMulti ) { |
| 44 |
if ( null === option ) { |
| 45 |
this.props.onChange([]); |
| 46 |
} else { |
| 47 |
const selected = Array.isArray(option) ? option : [option]; |
| 48 |
this.props.onChange(selected.map(option => option.value)); |
| 49 |
} |
| 50 |
} else { |
| 51 |
this.props.onChange(option.value); |
| 52 |
} |
| 53 |
}} |
| 54 |
styles={{ |
| 55 |
control: (provided) => ({ |
| 56 |
...provided, |
| 57 |
backgroundColor: 'white', |
| 58 |
}), |
| 59 |
container: (provided) => ({ |
| 60 |
...provided, |
| 61 |
width: '100%', |
| 62 |
maxWidth: this.props.width ? this.props.width : '600px', |
| 63 |
}), |
| 64 |
}} |
| 65 |
{ ...customProps } |
| 66 |
/> |
| 67 |
); |
| 68 |
} |
| 69 |
} |