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 "./style.css";
import { startTransition, useMemo, useState } from "react";
import * as Ariakit from "@ariakit/react";
import { matchSorter } from "match-sorter";
import list from "./list.js";
export default function Example() {
const [searchValue, setSearchValue] = useState("");
const matches = useMemo(() => matchSorter(list, searchValue), [searchValue]);
return (
<div className="wrapper">
startTransition(() => setSearchValue(value));
}}
>
<label className="label">
Your favorite food
</label>
{matches.length ? (
matches.map((value) => (
key={value}
className="combobox-item"
/>
))
) : (
<div className="no-results">No results found</div>
)}
</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("");
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]);
Follow updates
Join 1,000+ subscribers and receive monthly updates with the latest improvements on Examples.