Search with suggestions
A city search box that highlights the matching letters, groups results, remembers recent searches and is fully usable by keyboard.
"use client";
import {
useId,
useRef,
useState,
type KeyboardEvent,
type ReactElement,
} from "react";
import "./search-combobox.css";
type Place = { name: string; country: string; group: "Cities" | "Airports" };
const PLACES: Place[] = [
{ name: "Lisbon", country: "Portugal", group: "Cities" },
{ name: "Lima", country: "Peru", group: "Cities" },
{ name: "Lyon", country: "France", group: "Cities" },
{ name: "London", country: "United Kingdom", group: "Cities" },
{ name: "Los Angeles", country: "United States", group: "Cities" },
{ name: "Ljubljana", country: "Slovenia", group: "Cities" },
{ name: "Osaka", country: "Japan", group: "Cities" },
{ name: "Oslo", country: "Norway", group: "Cities" },
{ name: "Seoul", country: "South Korea", group: "Cities" },
{ name: "Berlin", country: "Germany", group: "Cities" },
{
name: "Lisbon Humberto Delgado (LIS)",
country: "Portugal",
group: "Airports",
},
{
name: "London Heathrow (LHR)",
country: "United Kingdom",
group: "Airports",
},
{
name: "Los Angeles International (LAX)",
country: "United States",
group: "Airports",
},
{ name: "Oslo Gardermoen (OSL)", country: "Norway", group: "Airports" },
];
/** Wrap the matched part of `text` in <mark>. */
function highlight(text: string, q: string): ReactElement {
const i = text.toLowerCase().indexOf(q.toLowerCase());
if (!q || i < 0) return <>{text}</>;
return (
<>
{text.slice(0, i)}
<mark>{text.slice(i, i + q.length)}</mark>
{text.slice(i + q.length)}
</>
);
}
/**
* SearchCombobox (ARIA 1.2 combobox + listbox)
* - Focus stays in the input; arrows move a virtual "active" option (aria-activedescendant).
* - With an empty query, recent picks are shown instead of results.
*/
export function SearchCombobox({
theme = "light",
}: {
theme?: "light" | "dark";
}) {
const id = useId();
const [q, setQ] = useState("");
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
const [recent, setRecent] = useState<Place[]>([PLACES[3], PLACES[7]]);
const [picked, setPicked] = useState<Place | null>(null);
const input = useRef<HTMLInputElement>(null);
const query = q.trim();
const results = query
? PLACES.filter((p) =>
`${p.name} ${p.country}`.toLowerCase().includes(query.toLowerCase()),
).slice(0, 7)
: recent;
const groups = query
? (["Cities", "Airports"] as const)
.map((g) => ({ label: g, items: results.filter((r) => r.group === g) }))
.filter((g) => g.items.length)
: [{ label: "Recent", items: results }];
const flat = groups.flatMap((g) => g.items);
const choose = (p: Place) => {
setPicked(p);
setQ(p.name);
setOpen(false);
setRecent((r) => [p, ...r.filter((x) => x !== p)].slice(0, 3));
};
const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setOpen(true);
setActive((a) => (a + 1) % Math.max(flat.length, 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((a) => (a - 1 + flat.length) % Math.max(flat.length, 1));
} else if (e.key === "Enter" && open && flat[active]) {
e.preventDefault();
choose(flat[active]);
} else if (e.key === "Escape") {
if (open) setOpen(false);
else setQ("");
}
};
let n = -1;
return (
<div className="gu-combo" data-theme={theme}>
<label htmlFor={id}>Where to?</label>
<div className="gu-combo__field">
<svg viewBox="0 0 24 24" aria-hidden="true" className="gu-combo__glass">
<circle cx="11" cy="11" r="6.5" />
<path d="m16 16 4.5 4.5" />
</svg>
<input
ref={input}
id={id}
value={q}
placeholder="Search cities or airports"
role="combobox"
aria-expanded={open && flat.length > 0}
aria-controls={`${id}-list`}
aria-autocomplete="list"
aria-activedescendant={
open && flat[active] ? `${id}-o${active}` : undefined
}
autoComplete="off"
onChange={(e) => {
setQ(e.target.value);
setActive(0);
setOpen(true);
setPicked(null);
}}
onFocus={() => setOpen(true)}
onBlur={() => setTimeout(() => setOpen(false), 120)}
onKeyDown={onKey}
/>
{q && (
<button
type="button"
className="gu-combo__clear"
aria-label="Clear search"
onClick={() => {
setQ("");
setPicked(null);
input.current?.focus();
}}
>
<svg viewBox="0 0 16 16" aria-hidden="true">
<path d="m4 4 8 8m0-8-8 8" />
</svg>
</button>
)}
</div>
{open && (
<div className="gu-combo__pop">
{flat.length ? (
<ul id={`${id}-list`} role="listbox" aria-label="Places">
{groups.map((g) => (
<li key={g.label} role="presentation">
<p className="gu-combo__group" aria-hidden="true">
{g.label}
</p>
<ul role="group" aria-label={g.label}>
{g.items.map((p) => {
n++;
const i = n;
return (
<li
key={p.name}
id={`${id}-o${i}`}
role="option"
aria-selected={i === active}
onMouseDown={(e) => e.preventDefault()}
onMouseMove={() => setActive(i)}
onClick={() => choose(p)}
>
<span className="gu-combo__pin" aria-hidden="true">
{p.group === "Airports"
? "✈"
: g.label === "Recent"
? "↺"
: "●"}
</span>
<span>
<b>{highlight(p.name, query)}</b>
<small>{highlight(p.country, query)}</small>
</span>
</li>
);
})}
</ul>
</li>
))}
</ul>
) : (
<p className="gu-combo__none" role="status">
No places match “{query}”. Try a city name or a 3-letter airport
code.
</p>
)}
</div>
)}
<p className="gu-combo__picked" role="status">
{picked ? `Flying to ${picked.name}, ${picked.country}.` : ""}
</p>
</div>
);
}
Paste this into ChatGPT, Claude, Cursor, v0, Lovable or Bolt. It describes the layout, motion, colors and accessibility and includes the code, so the AI can rebuild it in any framework.
# Build this UI piece: Search with suggestions
You are a senior front-end engineer. Recreate the piece below in my project. If I don't say which framework I use, ask once, then build it in that framework (React, Vue, Svelte, Angular, Astro, plain HTML/CSS/JS or anything else). Keep the behavior, motion, colors, spacing and accessibility exactly as described. Keep the code clean and commented for beginners.
## What it is
A travel "Where to?" search combobox. Empty, it shows recent searches; typing filters cities and airports into groups with the matched letters underlined in orange. Fully keyboard driven.
## Layout and look
- Big label (21px, weight 900). 56px pill input with a search icon on the left and a 40px round clear button on the right.
- Popover below: white (dark #1f1f23), radius 20px, soft shadow, max 340px tall, scrolls. Group headings small and muted.
- Option rows 52px: a 34px icon tile (dot for cities, plane for airports, ↺ for recent), name in bold, country muted. Active row has a faint background and the tile turns orange.
- Matches: transparent background, 3px orange underline.
## Behavior and motion
1. Filter by name + country (case-insensitive), max 7, grouped "Cities" / "Airports".
2. ArrowUp/Down move the active option (focus stays in the input), Enter picks, Escape closes then clears.
3. Picking fills the input, adds to recent (max 3) and announces "Flying to Lisbon, Portugal."
4. Popover opens with a 220ms fade/scale from the top.
5. No results: a helpful message.
## Touch
52px rows; mousedown is prevented on options so the input does not blur before the click.
## Accessibility
- role="combobox", aria-expanded, aria-controls, aria-activedescendant; listbox with grouped options.
- prefers-reduced-motion: no open animation.
## Props
theme. Replace the PLACES array with your data or an API call.
## Reference implementation
The original is written in React with one plain CSS file. Dependencies: none (plain React and CSS). Translate it faithfully; do not add new libraries unless my framework needs them.
### SearchCombobox.tsx
```tsx
"use client";
import {
useId,
useRef,
useState,
type KeyboardEvent,
type ReactElement,
} from "react";
import "./search-combobox.css";
type Place = { name: string; country: string; group: "Cities" | "Airports" };
const PLACES: Place[] = [
{ name: "Lisbon", country: "Portugal", group: "Cities" },
{ name: "Lima", country: "Peru", group: "Cities" },
{ name: "Lyon", country: "France", group: "Cities" },
{ name: "London", country: "United Kingdom", group: "Cities" },
{ name: "Los Angeles", country: "United States", group: "Cities" },
{ name: "Ljubljana", country: "Slovenia", group: "Cities" },
{ name: "Osaka", country: "Japan", group: "Cities" },
{ name: "Oslo", country: "Norway", group: "Cities" },
{ name: "Seoul", country: "South Korea", group: "Cities" },
{ name: "Berlin", country: "Germany", group: "Cities" },
{
name: "Lisbon Humberto Delgado (LIS)",
country: "Portugal",
group: "Airports",
},
{
name: "London Heathrow (LHR)",
country: "United Kingdom",
group: "Airports",
},
{
name: "Los Angeles International (LAX)",
country: "United States",
group: "Airports",
},
{ name: "Oslo Gardermoen (OSL)", country: "Norway", group: "Airports" },
];
/** Wrap the matched part of `text` in <mark>. */
function highlight(text: string, q: string): ReactElement {
const i = text.toLowerCase().indexOf(q.toLowerCase());
if (!q || i < 0) return <>{text}</>;
return (
<>
{text.slice(0, i)}
<mark>{text.slice(i, i + q.length)}</mark>
{text.slice(i + q.length)}
</>
);
}
/**
* SearchCombobox (ARIA 1.2 combobox + listbox)
* - Focus stays in the input; arrows move a virtual "active" option (aria-activedescendant).
* - With an empty query, recent picks are shown instead of results.
*/
export function SearchCombobox({
theme = "light",
}: {
theme?: "light" | "dark";
}) {
const id = useId();
const [q, setQ] = useState("");
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
const [recent, setRecent] = useState<Place[]>([PLACES[3], PLACES[7]]);
const [picked, setPicked] = useState<Place | null>(null);
const input = useRef<HTMLInputElement>(null);
const query = q.trim();
const results = query
? PLACES.filter((p) =>
`${p.name} ${p.country}`.toLowerCase().includes(query.toLowerCase()),
).slice(0, 7)
: recent;
const groups = query
? (["Cities", "Airports"] as const)
.map((g) => ({ label: g, items: results.filter((r) => r.group === g) }))
.filter((g) => g.items.length)
: [{ label: "Recent", items: results }];
const flat = groups.flatMap((g) => g.items);
const choose = (p: Place) => {
setPicked(p);
setQ(p.name);
setOpen(false);
setRecent((r) => [p, ...r.filter((x) => x !== p)].slice(0, 3));
};
const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setOpen(true);
setActive((a) => (a + 1) % Math.max(flat.length, 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((a) => (a - 1 + flat.length) % Math.max(flat.length, 1));
} else if (e.key === "Enter" && open && flat[active]) {
e.preventDefault();
choose(flat[active]);
} else if (e.key === "Escape") {
if (open) setOpen(false);
else setQ("");
}
};
let n = -1;
return (
<div className="gu-combo" data-theme={theme}>
<label htmlFor={id}>Where to?</label>
<div className="gu-combo__field">
<svg viewBox="0 0 24 24" aria-hidden="true" className="gu-combo__glass">
<circle cx="11" cy="11" r="6.5" />
<path d="m16 16 4.5 4.5" />
</svg>
<input
ref={input}
id={id}
value={q}
placeholder="Search cities or airports"
role="combobox"
aria-expanded={open && flat.length > 0}
aria-controls={`${id}-list`}
aria-autocomplete="list"
aria-activedescendant={
open && flat[active] ? `${id}-o${active}` : undefined
}
autoComplete="off"
onChange={(e) => {
setQ(e.target.value);
setActive(0);
setOpen(true);
setPicked(null);
}}
onFocus={() => setOpen(true)}
onBlur={() => setTimeout(() => setOpen(false), 120)}
onKeyDown={onKey}
/>
{q && (
<button
type="button"
className="gu-combo__clear"
aria-label="Clear search"
onClick={() => {
setQ("");
setPicked(null);
input.current?.focus();
}}
>
<svg viewBox="0 0 16 16" aria-hidden="true">
<path d="m4 4 8 8m0-8-8 8" />
</svg>
</button>
)}
</div>
{open && (
<div className="gu-combo__pop">
{flat.length ? (
<ul id={`${id}-list`} role="listbox" aria-label="Places">
{groups.map((g) => (
<li key={g.label} role="presentation">
<p className="gu-combo__group" aria-hidden="true">
{g.label}
</p>
<ul role="group" aria-label={g.label}>
{g.items.map((p) => {
n++;
const i = n;
return (
<li
key={p.name}
id={`${id}-o${i}`}
role="option"
aria-selected={i === active}
onMouseDown={(e) => e.preventDefault()}
onMouseMove={() => setActive(i)}
onClick={() => choose(p)}
>
<span className="gu-combo__pin" aria-hidden="true">
{p.group === "Airports"
? "✈"
: g.label === "Recent"
? "↺"
: "●"}
</span>
<span>
<b>{highlight(p.name, query)}</b>
<small>{highlight(p.country, query)}</small>
</span>
</li>
);
})}
</ul>
</li>
))}
</ul>
) : (
<p className="gu-combo__none" role="status">
No places match “{query}”. Try a city name or a 3-letter airport
code.
</p>
)}
</div>
)}
<p className="gu-combo__picked" role="status">
{picked ? `Flying to ${picked.name}, ${picked.country}.` : ""}
</p>
</div>
);
}
```
### search-combobox.css
```css
/* SearchCombobox: change these colors to match your brand. */
.gu-combo {
--field: #fbf8f2;
--pop: #ffffff;
--text: #0e0e10;
--muted: #57534b;
--line: rgb(14 14 16 / 0.16);
--active: rgb(14 14 16 / 0.07);
--mark: #ff5a1f;
--focus: #2b35ff;
position: relative;
display: grid;
gap: 8px;
width: min(100%, 440px);
color: var(--text);
font-family: system-ui, sans-serif;
}
.gu-combo[data-theme="dark"] {
--field: #18181b;
--pop: #1f1f23;
--text: #f3eee3;
--muted: #aea89c;
--line: rgb(243 238 227 / 0.16);
--active: rgb(243 238 227 / 0.08);
--focus: #d7ff3a;
}
.gu-combo > label {
font-size: 1.3rem;
font-weight: 900;
letter-spacing: -0.02em;
}
.gu-combo__field {
position: relative;
}
.gu-combo__glass {
position: absolute;
top: 50%;
left: 16px;
width: 20px;
translate: 0 -50%;
fill: none;
stroke: var(--muted);
stroke-width: 2;
stroke-linecap: round;
pointer-events: none;
}
.gu-combo input {
width: 100%;
height: 56px;
padding: 0 48px 0 46px;
border: 1.5px solid var(--line);
border-radius: 999px;
outline: none;
background: var(--field);
color: inherit;
font: inherit;
font-size: 1rem;
}
.gu-combo input:focus {
border-color: var(--focus);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--focus) 18%, transparent);
}
.gu-combo__clear {
position: absolute;
top: 8px;
right: 8px;
display: grid;
place-items: center;
width: 40px;
height: 40px;
border: 0;
border-radius: 50%;
background: var(--active);
color: var(--text);
cursor: pointer;
}
.gu-combo__clear:focus-visible {
outline: 2px solid var(--focus);
}
.gu-combo__clear svg {
width: 14px;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
}
.gu-combo__pop {
position: absolute;
top: calc(100% - 26px);
left: 0;
right: 0;
z-index: 5;
max-height: 340px;
overflow: auto;
padding: 8px;
border: 1px solid var(--line);
border-radius: 20px;
background: var(--pop);
box-shadow: 0 24px 48px -20px rgb(0 0 0 / 0.35);
transform-origin: top;
animation: gu-combo-open 0.22s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes gu-combo-open {
from {
opacity: 0;
transform: translateY(-6px) scaleY(0.96);
}
}
.gu-combo__pop ul {
margin: 0;
padding: 0;
list-style: none;
}
.gu-combo__group {
margin: 6px 10px 4px;
color: var(--muted);
font-size: 0.75rem;
font-weight: 800;
}
.gu-combo [role="option"] {
display: flex;
align-items: center;
gap: 12px;
min-height: 52px;
padding: 6px 10px;
border-radius: 12px;
cursor: pointer;
}
.gu-combo [role="option"][aria-selected="true"] {
background: var(--active);
}
.gu-combo [role="option"] > span:last-child {
display: grid;
min-width: 0;
}
.gu-combo [role="option"] b {
overflow: hidden;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
.gu-combo [role="option"] small {
color: var(--muted);
}
.gu-combo mark {
background: none;
color: inherit;
text-decoration: underline 3px var(--mark);
text-underline-offset: 3px;
}
.gu-combo__pin {
display: grid;
flex: none;
place-items: center;
width: 34px;
height: 34px;
border-radius: 10px;
background: var(--active);
font-size: 0.8rem;
}
.gu-combo [aria-selected="true"] .gu-combo__pin {
background: var(--mark);
color: #0e0e10;
}
.gu-combo__none {
margin: 0;
padding: 18px 12px;
color: var(--muted);
text-align: center;
}
.gu-combo__picked {
min-height: 1.3em;
margin: 0;
color: var(--muted);
font-size: 0.9rem;
}
@media (prefers-reduced-motion: reduce) {
.gu-combo__pop {
animation: none;
}
}
```
You might also want
Next piece: Settings togglesTag input
Components, intermediate
Command menu
Components, intermediate
Date range picker
Components, advanced