import { useState } from 'react' import { useCombobox } from 'downshift' import classnames from 'classnames' type DownshiftInputProps = { items: string[] inputValue: string setValue: React.Dispatch> } & React.InputHTMLAttributes const filterItemsByInputValue = ( items: DownshiftInputProps['items'], inputValue: DownshiftInputProps['inputValue'] ) => items.filter(item => item.toLowerCase().includes(inputValue.toLowerCase())) function DownshiftInput({ items, inputValue, placeholder, setValue, }: DownshiftInputProps) { const [inputItems, setInputItems] = useState(items) const { isOpen, getMenuProps, getInputProps, getComboboxProps, getItemProps, openMenu, selectedItem, } = useCombobox({ inputValue, items: inputItems, initialSelectedItem: inputValue, onSelectedItemChange: ({ selectedItem }) => { setValue(selectedItem ?? '') }, onInputValueChange: ({ inputValue = '' }) => { setInputItems(filterItemsByInputValue(items, inputValue)) }, onStateChange: ({ type }) => { if (type === useCombobox.stateChangeTypes.FunctionOpenMenu) { setInputItems(filterItemsByInputValue(items, inputValue)) } }, }) return (
) => { setValue(event.target.value) }, onFocus: () => { if (!isOpen) { openMenu() } }, })} className="form-control" type="text" placeholder={placeholder} />
    {inputItems.map((item, index) => (
  • {item}
  • ))}
) } export default DownshiftInput