| 1 |
import Select from 'react-select'; |
| 2 |
const useState = wp.element.useState; |
| 3 |
|
| 4 |
const { __ } = wp.i18n; |
| 5 |
|
| 6 |
const SelectMultipleField = (props) => { |
| 7 |
|
| 8 |
let options = []; |
| 9 |
props.selectOptions.map((selectOption, index) => { |
| 10 |
options.push({value: selectOption.value, label: selectOption.text}) |
| 11 |
}) |
| 12 |
|
| 13 |
/** |
| 14 |
* |
| 15 |
* Note: This should be done because the "value" attribute of the react-select |
| 16 |
* component should be an object with the following structure: (and not just |
| 17 |
* a string like the "value" attribute of the "select" HTML element) |
| 18 |
* |
| 19 |
* { |
| 20 |
* value: 'value', |
| 21 |
* label: 'label' |
| 22 |
* } |
| 23 |
* |
| 24 |
* @param value |
| 25 |
* @returns {*} |
| 26 |
*/ |
| 27 |
function getOptionsObject(value){ |
| 28 |
|
| 29 |
let selectedItems = []; |
| 30 |
|
| 31 |
//check if "value" is an array |
| 32 |
if(Array.isArray(value)){ |
| 33 |
value.forEach(function(item, index){ |
| 34 |
const selectedItem = options.find(function(item2) { |
| 35 |
if(item2.value === item){ |
| 36 |
return item2; |
| 37 |
} |
| 38 |
}); |
| 39 |
selectedItems.push(selectedItem); |
| 40 |
}); |
| 41 |
} |
| 42 |
|
| 43 |
return selectedItems; |
| 44 |
|
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Customize the style of the react-select component. |
| 49 |
* |
| 50 |
* References for react-select style customizations: |
| 51 |
* |
| 52 |
* - https://stackoverflow.com/questions/54218351/changing-height-of-react-select-component |
| 53 |
* - https://react-select.com/styles |
| 54 |
* - https://react-select.com/styles#inner-components |
| 55 |
* |
| 56 |
* @type {{input: (function(*, *): *&{margin: string}), valueContainer: (function(*, *): *&{padding: string, height: string}), indicatorSeparator: (function(*): {display: string}), control: (function(*, *): *&{minHeight: string, boxShadow: null, height: string}), indicatorsContainer: (function(*, *): *&{height: string})}} |
| 57 |
*/ |
| 58 |
const styles = { |
| 59 |
control: (provided, state) => ({ |
| 60 |
...provided, |
| 61 |
width: 440, // Set your custom width here |
| 62 |
}), |
| 63 |
}; |
| 64 |
|
| 65 |
return ( |
| 66 |
<div className={'react-select-container'}> |
| 67 |
<Select |
| 68 |
value={getOptionsObject(props.value)} |
| 69 |
onChange={(event) => { |
| 70 |
props.onChange(event, props.name) |
| 71 |
}} |
| 72 |
options={options} |
| 73 |
isMulti={true} |
| 74 |
styles={styles} |
| 75 |
placeholder={__('Choose an Option ...', 'ultimate-markdown')} |
| 76 |
> |
| 77 |
</Select> |
| 78 |
<p className="components-base-control__help">{props.help}</p> |
| 79 |
</div> |
| 80 |
); |
| 81 |
|
| 82 |
}; |
| 83 |
|
| 84 |
export default SelectMultipleField; |