| 1 |
import Select from '../atoms/select'; |
| 2 |
|
| 3 |
import './select2.scss'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Default settings of the select 2 |
| 7 |
* |
| 8 |
* @return {{placeholder: string, allowClear: boolean, dir: string}} |
| 9 |
*/ |
| 10 |
|
| 11 |
const getDefaultSettings = () => ( { |
| 12 |
allowClear: true, |
| 13 |
placeholder: '', |
| 14 |
dir: elementorCommon.config.isRTL ? 'rtl' : 'ltr', |
| 15 |
} ); |
| 16 |
/** |
| 17 |
* Main component |
| 18 |
* |
| 19 |
* @param {*} props |
| 20 |
* @return {*} component |
| 21 |
* @function Object() { [native code] } |
| 22 |
*/ |
| 23 |
export default function Select2( props ) { |
| 24 |
const ref = React.useRef( null ); |
| 25 |
|
| 26 |
// Initiate the select 2 library, call to onReady after initiate, and |
| 27 |
// listen to select event on the select instance. |
| 28 |
React.useEffect( () => { |
| 29 |
const $select2 = jQuery( ref.current ) |
| 30 |
.select2( { |
| 31 |
...getDefaultSettings(), |
| 32 |
...props.settings, |
| 33 |
placeholder: props.placeholder, |
| 34 |
} ) |
| 35 |
.on( 'select2:select select2:unselect', props.onChange ); |
| 36 |
|
| 37 |
if ( props.onReady ) { |
| 38 |
props.onReady( $select2 ); |
| 39 |
} |
| 40 |
|
| 41 |
return () => { |
| 42 |
$select2.select2( 'destroy' ).off( 'select2:select select2:unselect' ); |
| 43 |
}; |
| 44 |
}, [ props.settings, props.options ] ); |
| 45 |
|
| 46 |
// Listen to changes in the prop `value`, if changed update the select 2. |
| 47 |
React.useEffect( () => { |
| 48 |
jQuery( ref.current ).val( props.value ).trigger( 'change' ); |
| 49 |
}, [ props.value ] ); |
| 50 |
|
| 51 |
return <Select |
| 52 |
multiple={ props.multiple } |
| 53 |
value={ props.value } |
| 54 |
onChange={ props.onChange } |
| 55 |
elRef={ ref } |
| 56 |
options={ props.options } |
| 57 |
placeholder={ props.placeholder } |
| 58 |
/>; |
| 59 |
} |
| 60 |
Select2.propTypes = { |
| 61 |
value: PropTypes.oneOfType( [ PropTypes.array, PropTypes.string ] ), |
| 62 |
onChange: PropTypes.func, |
| 63 |
onReady: PropTypes.func, |
| 64 |
options: PropTypes.array, |
| 65 |
settings: PropTypes.object, |
| 66 |
multiple: PropTypes.bool, |
| 67 |
placeholder: PropTypes.string, |
| 68 |
}; |
| 69 |
Select2.defaultProps = { |
| 70 |
settings: {}, |
| 71 |
options: [], |
| 72 |
dependencies: [], |
| 73 |
placeholder: '', |
| 74 |
}; |
| 75 |
|