Ariakit
/

Combobox filtering

Listing suggestions in a Combobox component based on the input value using React.startTransition to ensure the UI remains responsive during typing.

import * as Ariakit from "@ariakit/react";
import { matchSorter } from "match-sorter";
import { startTransition, useMemo, useState } from "react";
import list from "./list.ts";
import "./style.css";
export default function Example() {
const [searchValue, setSearchValue] = useState("");
const matches = useMemo(() => matchSorter(list, searchValue), [searchValue]);
return (
setValue={(value) => {
startTransition(() => setSearchValue(value));
}}
>
<Ariakit.ComboboxLabel className="label">
Your favorite food
<Ariakit.Combobox placeholder="e.g., Apple" className="combobox" />
<Ariakit.ComboboxPopover gutter={8} sameWidth className="popover">
{matches.length ? (
matches.map((value) => (
key={value}
value={value}
className="combobox-item"
/>
))
) : (
<div className="no-results">No results found</div>
)}
);
}

Components

Setting the search value

In this example, we're using the setValue prop from the ComboboxProvider component to set the search value when the user types. The state is updated in a React.startTransition callback to ensure the UI remains responsive during typing.

const [searchValue, setSearchValue] = useState("");
setValue={(value) => {
startTransition(() => setSearchValue(value));
}}
>

You can learn more about controlling state on the Component providers guide.

Filtering items

The Combobox component is agnostic to the filtering method you use. Its concern lies solely in the items you render through the ComboboxItem component. You have the flexibility to select the filtering strategy that suits your specific use case.

In this example, we use the match-sorter library to filter and sort items based on the search value. Another option is fast-fuzzy, which employs advanced algorithms for fuzzy search.

const matches = useMemo(() => {
return matchSorter(list, searchValue);
}, [searchValue]);
matches.map((value) => <ComboboxItem key={value} value={value} />);

Stay tuned

Join 1,000+ subscribers and receive monthly tips & updates on new Ariakit content.

No spam. Unsubscribe anytime. Read latest issue