When using react-select, search results are ordered alphabetically by default. This is a good default but not so nice if I have an exact match that is not first alphabetically. For example, a user may have the following options:
With these options, the user may search for 'react' and not be any closer to selecting the option that exactly matches the search term. Is there any way to optimize for exact matches?
In react-select
you can pass a filterOption
property to change how the filtering works. They provide a nice api to do what you want, which is start matching from the beginning of the string rather than anywhere in the string. That would look something like this
filterOption={createFilter({ matchFrom: "start" })}
where createFilter
is imported from react-select
react-select
has a prop if you want to have a custom filter - filterOption
.
If you want to show better matches based on what a user queries, use match-sorter in combination with onInputChange
of react-select
to create a custom filter. Here's a working demo.
There are two select inputs. Type l
and observe the difference in suggestions.
@ron4ex has a great answer here. Just wanted to offer another similar solution as I had 1 big issue with match-sorter.
Issue with match-sorter:
Enter new solution: Fuse:
const fuse = new Fuse(relationshipTypes, { keys: ["label"] });
<Select>
onInputChange={inputValue => {
setRelationshipOptions(
fuse.search(inputValue).map(value => value.item)
);
}}
</Select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With