index.tsx
40 lines
| 1 | import styles from './FormSelect.module.scss'; |
| 2 | import cx from 'classnames'; |
| 3 | import Input from '@givewp/components/ListTable/Input'; |
| 4 | |
| 5 | export const FormSelect = ({options, name, placeholder = '', ariaLabel = '', onChange, ...rest}) => { |
| 6 | return ( |
| 7 | <> |
| 8 | <Input |
| 9 | type="search" |
| 10 | className={cx(styles.formSelect)} |
| 11 | list={`giveSearchSelect-${name}`} |
| 12 | onChange={updateSearchableSelect(options, name, onChange)} |
| 13 | autoComplete={'off'} |
| 14 | aria-label={ariaLabel} |
| 15 | placeholder={placeholder} |
| 16 | {...rest} |
| 17 | /> |
| 18 | <datalist id={`giveSearchSelect-${name}`} onChange={onChange}> |
| 19 | {options.map(({value, text}) => ( |
| 20 | <option key={`${value}${text}`} value={value === '0' ? text : `${text} (#${value})`} /> |
| 21 | ))} |
| 22 | </datalist> |
| 23 | </> |
| 24 | ); |
| 25 | }; |
| 26 | |
| 27 | const updateSearchableSelect = (options, name, onChange) => { |
| 28 | return (event) => { |
| 29 | if (event.target.value === '') { |
| 30 | onChange(name, 0); |
| 31 | } |
| 32 | const selectedIndex = options.findIndex((option) => { |
| 33 | return event.target.value.endsWith(`(#${option.value})`); |
| 34 | }); |
| 35 | if (selectedIndex > -1) { |
| 36 | onChange(name, options[selectedIndex].value); |
| 37 | } |
| 38 | }; |
| 39 | }; |
| 40 |