Combobox with links
Using a Combobox with items rendered as links that can be clicked with keyboard and mouse. This is useful for creating an accessible page search input in React.
import "./style.css";
import { startTransition, useMemo, useState } from "react";
import * as Ariakit from "@ariakit/react";
import { matchSorter } from "match-sorter";
import { NewWindow } from "./icons.jsx";
const links = [
{
href: "https://twitter.com/ariakitjs",
children: "Twitter",
target: "_blank",
},
{
href: "https://www.facebook.com/ariakitjs",
children: "Facebook",
target: "_blank",
},
{
href: "https://www.instagram.com/ariakitjs",
children: "Instagram",
target: "_blank",
},
{ href: "https://ariakit.org", children: "Ariakit.org" },
];
export default function Example() {
const [open, setOpen] = useState(false);
const [searchValue, setSearchValue] = useState("");
const matches = useMemo(() => {
return matchSorter(links, searchValue, {
keys: ["children"],
baseSort: (a, b) => (a.index < b.index ? -1 : 1),
});
}, [searchValue]);
return (
<div className="wrapper">
>
<label className="label">
Links
placeholder="e.g., Twitter"
className="combobox"
/>
</label>
className="popover"
>
{matches.length ? (
matches.map(({ children, ...props }) => (
key={children}
className="combobox-item"
render={<a {...props} />}
>
{children}
{props.target === "_blank" && (
<NewWindow className="combobox-item-icon" />
)}
))
) : (
<div className="no-results">No results found</div>
)}
</div>
);
}
Components
Rendering a link
The ComboboxItem
component can be rendered as a link using the render
prop:
{...specificComboboxItemProps}
render={<a {...specificAnchorProps} />}
/>
You can learn more about this pattern on the Composition guide.
Link features
When rendered as a link, ComboboxItem
supports all native link behaviors, including:
Open in a new tab in the background: ⌘ Enter
Open in a new tab and switch to the tab: ⌘ Shift Enter
Open in new window: Shift Enter
Download: Alt Enter
Follow updates
Join 1,000+ subscribers and receive monthly updates with the latest improvements on Examples.