Created
April 25, 2022 18:02
-
-
Save guillermodlpa/078a7b66acd4473b0eadedc50949bd4e to your computer and use it in GitHub Desktop.
Component I made while developing Travelmap, but ended up not keeping. This could be useful in the future.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Select, SelectExtendedProps } from 'grommet'; | |
import { useState } from 'react'; | |
export interface Option { | |
label: string; | |
value: string; | |
} | |
interface SearchableSelectProps extends SelectExtendedProps { | |
options: Option[]; | |
} | |
const SearchableSelect: React.FC<SearchableSelectProps> = ({ options, onChange, ...rest }) => { | |
const [filteredOptions, setFilteredOptions] = useState(options); | |
return ( | |
<Select | |
{...rest} | |
options={filteredOptions} | |
onChange={(...args) => { | |
if (onChange) { | |
onChange(...args); | |
} | |
setFilteredOptions(options); | |
}} | |
onSearch={(text) => { | |
// The line below escapes regular expression special characters: [ \ ^ $ . | ? * + ( ) | |
const escapedText = text.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&'); | |
const exp = new RegExp(escapedText, 'i'); | |
setFilteredOptions( | |
options.filter(({ label }) => typeof label === 'string' && exp.test(label)) | |
); | |
}} | |
/> | |
); | |
}; | |
export default SearchableSelect; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment