shadcn/ui combobox with objects

I am creating a Combobox based on shadcn/ui (https://ui.shadcn.com/docs/components/combobox) which uses cmdk (https://github.com/pacocoursey/cmdk), Popover and Dialog from Radix under the hood. The implementation in the docs uses the value of each <CommandItem> to filter. However, all my use cases are with objects with id and name keys where name is not unique. How should I be handling the filtering and onSelect ? My solution was to give id as the value and then add my own filter for <Command> as follows -
<Command
filter={(value, search) => {
const obj = myArrayOfObjects.find(
(stageTemplate) => stageTemplate._id.toString() === value
);
if (obj) {
if (
stageTemplate.name.toLowerCase().includes(search.toLowerCase())
)
return 1;
}
return 0;
}}
>
<Command
filter={(value, search) => {
const obj = myArrayOfObjects.find(
(stageTemplate) => stageTemplate._id.toString() === value
);
if (obj) {
if (
stageTemplate.name.toLowerCase().includes(search.toLowerCase())
)
return 1;
}
return 0;
}}
>
For the onSelect I have the following -
onSelect={(currentValue: string) => {
const obj = myArrayOfObjects.find((objs) => obj.id === currentValue);
if (obj) {
// handle on select
}
setOpen(false);
}}
onSelect={(currentValue: string) => {
const obj = myArrayOfObjects.find((objs) => obj.id === currentValue);
if (obj) {
// handle on select
}
setOpen(false);
}}
Does this make sense? Don't love that I am using Array.find() for each element to decide if it should be filtered out or not.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server