Skip to content

Commit

Permalink
filter options on search in combobox
Browse files Browse the repository at this point in the history
  • Loading branch information
yesyash committed Sep 1, 2024
1 parent ad89d7e commit 42e2641
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
22 changes: 18 additions & 4 deletions src/components/combobox.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { useState } from "react"

import {
Combobox as BaseCombobox,
ComboboxInput as BaseComboboxInput,
ComboboxOption as BaseComboboxOption,
ComboboxOptions as BaseComboboxOptions,
Field,
} from "@headlessui/react"
import { CheckIcon } from "lucide-react"

import { cn } from "@/utils/classname"
import { inter } from "@/utils/fonts"
Expand Down Expand Up @@ -42,17 +45,27 @@ export const Combobox = <T,>({
onInputChange,
errorMessage,
}: ComboboxProps<T>) => {
const [query, setQuery] = useState<string>("")
const filteredOptions = !query.length
? options
: options.filter((option) => option.label.toLowerCase().includes(query.toLowerCase()))

const handleInputChange = (value: string) => {
setQuery(value)
onInputChange && onInputChange(value)
}

return (
<Field>
{label && <Label>{label}</Label>}

<BaseCombobox value={value} onChange={onChange} immediate={immediate}>
<BaseCombobox value={value} onChange={onChange} immediate={immediate} onClose={() => setQuery("")}>
<BaseComboboxInput
aria-label={label}
placeholder={placeholder}
className="h-10 w-full rounded-lg border border-gray-200 px-4 outline-none ring ring-transparent transition focus:border-blue-400 focus:ring-blue-100"
displayValue={(option: TComboBoxOption<T>) => option?.label}
onChange={(e) => onInputChange && onInputChange(e.currentTarget.value)}
onChange={(e) => handleInputChange(e.currentTarget.value)}
/>

<BaseComboboxOptions
Expand All @@ -63,12 +76,13 @@ export const Combobox = <T,>({
inter.variable
)}
>
{options.map((option) => (
{filteredOptions.map((option) => (
<BaseComboboxOption
key={String(option.value)}
value={option}
className="px-4 py-2 data-[focus]:bg-blue-100"
className="group flex items-center gap-2 px-4 py-2 data-[focus]:bg-blue-100"
>
<CheckIcon className="invisible h-4 w-4 text-gray-500 group-data-[selected]:visible" />
{option.label}
</BaseComboboxOption>
))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ export const SkillListCombobox = ({ label, value, placeholder, errorMessage, onC
queryFn: SkillsApi.getAllSkills,
})

const options =
data?.map<TOption>((skill) => ({
value: skill.id,
label: skill.name,
})) ?? []
const options = data?.map<TOption>((skill) => ({ value: skill.id, label: skill.name })) ?? []

const selectedOption = options.find((option) => option.value === value) ?? null

Expand Down

0 comments on commit 42e2641

Please sign in to comment.