Skip to content

Instantly share code, notes, and snippets.

@guillermodlpa
Created April 25, 2022 18:02
Show Gist options
  • Save guillermodlpa/078a7b66acd4473b0eadedc50949bd4e to your computer and use it in GitHub Desktop.
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.
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