Skip to content
Product block

Header Search with Suggestions

The field in the header, not the palette over it: Enter searches for what you typed unless you arrowed to a suggestion, late responses are dropped by sequence number, and recent searches are removable one at a time.

357 lineslucide-reactAdded 27 Aug 2026Updated 11 Sept 2026
  • search
  • autocomplete
  • combobox
  • typeahead
  • suggestions

What's included

  • components/search-autocomplete.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add search-autocomplete

Or over MCP, from your editor's agent — no account needed.

License

Free to read, copy and install, for personal and non-commercial projects. Shipping it in client work or a paid product needs Pro ($79 once). The source lands in your repo and stops being ours — no attribution, nothing to upgrade.

Was this useful?

Start a page with this section — add more, order them, and leave with the page source.

Preview

Search for meri

Nothing matched. Press Enter to search everything for “meri” anyway.

0 suggestions. Enter searches for what you typed.

Rendered live in your current theme — this is the same component whose source is below, not a screenshot of it.

Source

components/search-autocomplete.tsx
'use client'

/**
 * <SearchAutocomplete> — the field in the header, not the palette over it.
 *
 * Command & Search had the palette, the shortcuts sheet, the results panel
 * and the applied-filters bar. The palette is a modal that takes the whole
 * screen and runs commands; this is the small field that lives in the
 * header, suggests as you type, and has to stay out of your way. They look
 * similar and behave nothing alike.
 *
 * THE ONE THING THIS GETS RIGHT THAT MOST DO NOT
 *
 * Enter submits what you typed. Not the first suggestion, not whatever the
 * list settled on while the request was in flight — the characters in the
 * box. A suggestion only wins if the person arrowed down to it, which they
 * did on purpose. Every "it searched for something I did not ask for"
 * complaint is this rule being broken, usually because the highlight
 * defaults to index 0 and Enter reads the highlight.
 *
 * LATE RESPONSES ARE DROPPED, NOT RENDERED
 *
 * Type four characters quickly and four requests are in the air; they can
 * land in any order, and the list you are pointing at can be replaced by
 * an older one a moment before you click. A sequence number guards it: a
 * response older than the newest one already shown is discarded. This is
 * the bug behind clicking a result and landing somewhere unrelated, and it
 * cannot be fixed with a debounce alone. (The stand-in below also clears
 * its timer on change, which a real `fetch` will not do for you unless you
 * carry an `AbortController` — keep the counter when you swap it out.)
 *
 * RECENT SEARCHES ARE REMOVABLE
 *
 * Anything the product remembers about a person has to be forgettable by
 * them, one item at a time — a search history you can only clear entirely
 * is a bad answer to somebody who typed one thing they regret.
 *
 * ACCESSIBILITY: the combobox pattern — the input keeps focus and points
 * at the active option with `aria-activedescendant`, the popup is a
 * `role="listbox"`, groups are `role="group"` with their own labels, and
 * the result count is announced through a polite live region. Hover does
 * not move the keyboard highlight.
 */

import * as React from 'react'
import { ArrowUpRight, Clock, CornerDownLeft, FileText, Search, User, X } from 'lucide-react'

export interface SearchEntity {
  id: string
  label: string
  detail: string
  group: string
  icon: React.ComponentType<{ className?: string }>
}

export interface SearchAutocompleteProps {
  entities?: SearchEntity[]
  recents?: string[]
  /** Simulated round-trip, so the out-of-order guard is visible in a demo. */
  latencyMs?: number
  /**
   * Opens with a query already typed. A closed, empty search field is a
   * picture of an input, not of this component.
   */
  initialQuery?: string
  className?: string
}

const DEFAULT_ENTITIES: SearchEntity[] = [
  { id: 'c1', label: 'Meridian Foods', detail: 'Customer · 41 seats · Scale', group: 'Customers', icon: User },
  { id: 'c2', label: 'Meridian Logistics', detail: 'Customer · 8 seats · Team', group: 'Customers', icon: User },
  { id: 'c3', label: 'Halden Group', detail: 'Customer · 120 seats · Enterprise', group: 'Customers', icon: User },
  { id: 'd1', label: 'Refunds policy', detail: 'Document · edited 3 days ago', group: 'Documents', icon: FileText },
  { id: 'd2', label: 'Merchant onboarding runbook', detail: 'Document · edited in June', group: 'Documents', icon: FileText },
  { id: 'd3', label: 'Q3 support metrics', detail: 'Document · edited yesterday', group: 'Documents', icon: FileText },
]

const DEFAULT_RECENTS = ['refund policy', 'meridian', 'seat count enterprise']


export function SearchAutocomplete({
  entities = DEFAULT_ENTITIES,
  recents = DEFAULT_RECENTS,
  latencyMs = 180,
  initialQuery = 'meri',
  className = '',
}: SearchAutocompleteProps) {
  /*
    Per-instance prefix for every id this block emits.

    The literals these replaced were a latent duplicate the moment the
    block appeared twice on one document, and `aria-labelledby` on a
    duplicated id resolves to the first match -- so the second copy was
    labelled by the first copy's heading. Client component, so `useId` is
    the right tool.
  */
  const uid = React.useId()

  const [query, setQuery] = React.useState(initialQuery)
  const [open, setOpen] = React.useState(Boolean(initialQuery))
  /* -1 means "nothing navigated to", which is what makes Enter honest. */
  const [active, setActive] = React.useState(-1)
  const [results, setResults] = React.useState<SearchEntity[]>([])
  const [pending, setPending] = React.useState(false)
  const [history, setHistory] = React.useState(recents)
  const [submitted, setSubmitted] = React.useState<string | null>(null)

  /* Monotonic counter: anything older than the newest render is dropped. */
  const seq = React.useRef(0)
  const shown = React.useRef(0)

  React.useEffect(() => {
    const q = query.trim().toLowerCase()
    if (!q) {
      setResults([])
      setPending(false)
      return
    }
    const mine = ++seq.current
    setPending(true)
    const timer = window.setTimeout(
      () => {
        /* The guard. A late response never overwrites a newer one. */
        if (mine < shown.current) return
        shown.current = mine
        setResults(
          entities.filter(
            (e) =>
              e.label.toLowerCase().includes(q) || e.detail.toLowerCase().includes(q),
          ),
        )
        setPending(false)
      },
      /* Uneven on purpose — even responses come back late. */
      mine % 2 === 0 ? latencyMs * 2 : latencyMs,
    )
    return () => window.clearTimeout(timer)
  }, [query, entities, latencyMs])

  React.useEffect(() => setActive(-1), [query])

  const grouped = React.useMemo(() => {
    const map = new Map<string, SearchEntity[]>()
    for (const r of results) map.set(r.group, [...(map.get(r.group) ?? []), r])
    return [...map.entries()]
  }, [results])
  const flat = grouped.flatMap(([, rows]) => rows)

  const submitQuery = (text: string) => {
    setSubmitted(text)
    setOpen(false)
    setHistory((h) => [text, ...h.filter((x) => x !== text)].slice(0, 5))
  }

  const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'ArrowDown') {
      event.preventDefault()
      setOpen(true)
      setActive((i) => (flat.length ? Math.min(i + 1, flat.length - 1) : -1))
    } else if (event.key === 'ArrowUp') {
      event.preventDefault()
      setActive((i) => Math.max(i - 1, -1))
    } else if (event.key === 'Escape') {
      setOpen(false)
      setActive(-1)
    } else if (event.key === 'Enter') {
      event.preventDefault()
      /* The rule: the highlight only wins if somebody moved to it. */
      if (active >= 0 && flat[active]) submitQuery(flat[active].label)
      else if (query.trim()) submitQuery(query.trim())
    }
  }

  const showRecents = open && !query.trim() && history.length > 0

  return (
    /*
      Bottom padding, not a stray value: the popup is absolutely positioned
      and adds nothing to the section's height, so any ancestor with
      `overflow: hidden` clips it. Reserve the room it opens into.
    */
    <section className={`mx-auto w-full max-w-xl px-4 pb-40 pt-16 sm:px-6 ${className}`}>
      <div className="relative">
        <label htmlFor={`${uid}-search-autocomplete`} className="sr-only">
          Search customers and documents
        </label>
        <Search
          aria-hidden
          className="pointer-events-none absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
        />
        <input
          id={`${uid}-search-autocomplete`}
          type="text"
          role="combobox"
          aria-expanded={open}
          aria-controls={`${uid}-search-autocomplete-listbox`}
          aria-autocomplete="list"
          aria-activedescendant={
            active >= 0 && flat[active] ? `search-option-${flat[active].id}` : undefined
          }
          value={query}
          onChange={(event) => {
            setQuery(event.target.value)
            setOpen(true)
            setSubmitted(null)
          }}
          onFocus={() => setOpen(true)}
          onKeyDown={onKeyDown}
          placeholder="Search customers and documents"
          className="h-11 w-full rounded-xl border border-field bg-background ps-9 pe-9 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
        />
        {query ? (
          <button
            type="button"
            onClick={() => {
              setQuery('')
              setSubmitted(null)
            }}
            className="absolute end-2 top-1/2 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          >
            <X aria-hidden className="h-4 w-4" />
            <span className="sr-only">Clear search</span>
          </button>
        ) : null}

        {open ? (
          <div
            id={`${uid}-search-autocomplete-listbox`}
            role="listbox"
            aria-label="Search suggestions"
            className="absolute inset-x-0 top-full z-10 mt-1 max-h-80 overflow-y-auto rounded-xl border border-border bg-popover p-1 shadow-lg"
          >
            {showRecents ? (
              <div role="group" aria-label="Recent searches">
                <p className="px-2.5 pb-1 pt-2 text-xs font-medium text-muted-foreground">
                  Recent
                </p>
                {history.map((h) => (
                  <div
                    key={h}
                    className="flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-foreground hover:bg-accent hover:text-accent-foreground"
                  >
                    <Clock aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                    <button
                      type="button"
                      onMouseDown={(event) => {
                        event.preventDefault()
                        setQuery(h)
                      }}
                      className="min-w-0 flex-1 truncate text-start text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                    >
                      {h}
                    </button>
                    {/* Forgettable one at a time, not only all at once. */}
                    <button
                      type="button"
                      onMouseDown={(event) => {
                        event.preventDefault()
                        setHistory((list) => list.filter((x) => x !== h))
                      }}
                      className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                    >
                      <X aria-hidden className="h-3 w-3" />
                      <span className="sr-only">Remove &ldquo;{h}&rdquo; from recent searches</span>
                    </button>
                  </div>
                ))}
              </div>
            ) : null}

            {query.trim() ? (
              <>
                {/* Always first, always the typed text — the Enter target. */}
                <div
                  role="option"
                  aria-selected={active === -1}
                  onMouseDown={(event) => {
                    event.preventDefault()
                    submitQuery(query.trim())
                  }}
                  className={`flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-2 text-sm ${
                    active === -1 ? 'bg-accent text-accent-foreground' : 'text-foreground'
                  }`}
                >
                  <Search aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                  <span className="min-w-0 flex-1 truncate">
                    Search for <strong className="font-semibold">{query.trim()}</strong>
                  </span>
                  <CornerDownLeft aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                </div>

                {grouped.map(([group, rows]) => (
                  <div key={group} role="group" aria-label={group}>
                    <p className="px-2.5 pb-1 pt-2 text-xs font-medium text-muted-foreground">
                      {group}
                    </p>
                    {rows.map((row) => {
                      const index = flat.indexOf(row)
                      const isActive = index === active
                      const Icon = row.icon
                      return (
                        <div
                          key={row.id}
                          id={`${uid}-search-option-${row.id}`}
                          role="option"
                          aria-selected={isActive}
                          onMouseDown={(event) => {
                            event.preventDefault()
                            submitQuery(row.label)
                          }}
                          className={`flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-2 ${
                            isActive ? 'bg-accent text-accent-foreground' : 'text-foreground'
                          }`}
                        >
                          <Icon aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                          <span className="min-w-0 flex-1">
                            <span className="block truncate text-sm">{row.label}</span>
                            <span className="block truncate text-xs text-muted-foreground">
                              {row.detail}
                            </span>
                          </span>
                          <ArrowUpRight
                            aria-hidden
                            className="h-3.5 w-3.5 shrink-0 text-muted-foreground"
                          />
                        </div>
                      )
                    })}
                  </div>
                ))}

                {!pending && results.length === 0 ? (
                  <p className="px-2.5 py-4 text-sm text-muted-foreground">
                    Nothing matched. Press Enter to search everything for
                    &ldquo;{query.trim()}&rdquo; anyway.
                  </p>
                ) : null}
              </>
            ) : null}
          </div>
        ) : null}
      </div>

      {/* Counts announced politely; the field keeps focus throughout. */}
      <p aria-live="polite" className="mt-3 min-h-5 text-xs text-muted-foreground">
        {submitted
          ? `Searched for “${submitted}”.`
          : pending
            ? 'Searching…'
            : query.trim()
              ? `${results.length} ${results.length === 1 ? 'suggestion' : 'suggestions'}. Enter searches for what you typed.`
              : 'Enter searches for exactly what you type. Arrow down to pick a suggestion instead.'}
      </p>
    </section>
  )
}

Before you paste

  • Styling is Tailwind utility classes on semantic tokens (bg-card, text-muted-foreground) — it inherits your theme instead of overriding it.
  • Install: npm i lucide-react
  • Every prop has a default, so it renders standalone before you wire it up.

Where it goes

Drop it at components/search-autocomplete.tsx and import it where you need the section:

import { SearchAutocomplete } from '@/components/search-autocomplete'

Customize

2 of this block’s props are simple enough to drive from here. Change them and the block below re-renders — it is the same component whose source is above, not a mock of it. Everything else it accepts is in the table underneath.

Props

Read out of the component’s own type and signature, so this cannot drift from the source below. Every prop has a default — the component renders standalone before you pass it anything.

PropTypeDefault
entitiesSearchEntity[]DEFAULT_ENTITIES
recentsstring[]DEFAULT_RECENTS
latencyMsSimulated round-trip, so the out-of-order guard is visible in a demo.number180
initialQueryOpens with a query already typed. A closed, empty search field is a picture of an input, not of this component.string'meri'
classNamestring''

Not using React?

The same block rendered once to markup, wrapped as a file your framework compiles. Tailwind classes are framework-agnostic, so the design transfers intact — the behaviour does not.

This block is interactive. The markup below is its initial state with the event handlers stripped — you will need to re-wire the behaviour in your framework.

search-autocomplete.html
<!--
  Header Search with Suggestions — markup from the Hoverlab catalog.

  This is the block rendered once to HTML and wrapped as a component
  file. It is not a port of the React source: the Tailwind classes carry
  the design, which is the part that took the work, and they are the same
  in every framework.

  This block is interactive in React and the handlers are NOT here.
  Buttons, toggles and menus render in their initial state and do
  nothing until you wire them up.
-->
<section class="mx-auto w-full max-w-xl px-4 pb-40 pt-16 sm:px-6 ">
  <div class="relative">
    <label for="_R_0_-search-autocomplete" class="sr-only">Search customers and documents</label>
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-search pointer-events-none absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden="true">
      <path d="m21 21-4.34-4.34"></path>
      <circle cx="11" cy="11" r="8"></circle>
    </svg>
    <input id="_R_0_-search-autocomplete" type="text" role="combobox" aria-expanded="true" aria-controls="_R_0_-search-autocomplete-listbox" aria-autocomplete="list" placeholder="Search customers and documents" class="h-11 w-full rounded-xl border border-field bg-background ps-9 pe-9 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background" value="meri" />
    <button type="button" class="absolute end-2 top-1/2 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x h-4 w-4" aria-hidden="true">
        <path d="M18 6 6 18"></path>
        <path d="m6 6 12 12"></path>
      </svg>
      <span class="sr-only">Clear search</span>
    </button>
    <div id="_R_0_-search-autocomplete-listbox" role="listbox" aria-label="Search suggestions" class="absolute inset-x-0 top-full z-10 mt-1 max-h-80 overflow-y-auto rounded-xl border border-border bg-popover p-1 shadow-lg">
      <div role="option" aria-selected="true" class="flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-2 text-sm bg-accent text-accent-foreground">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-search h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true">
          <path d="m21 21-4.34-4.34"></path>
          <circle cx="11" cy="11" r="8"></circle>
        </svg>
        <span class="min-w-0 flex-1 truncate">Search for <strong class="font-semibold">meri</strong></span>
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-corner-down-left h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true">
          <path d="M20 4v7a4 4 0 0 1-4 4H4"></path>
          <path d="m9 10-5 5 5 5"></path>
        </svg>
      </div>
      <p class="px-2.5 py-4 text-sm text-muted-foreground">Nothing matched. Press Enter to search everything for “meri” anyway.</p>
    </div>
  </div>
  <p aria-live="polite" class="mt-3 min-h-5 text-xs text-muted-foreground">0 suggestions. Enter searches for what you typed.</p>
</section>
  • This is rendered HTML, not a translation of the React source. The Tailwind classes carry the design and work in any framework.
  • It is one frame: the component in its initial state, with no props applied beyond the defaults.
  • This block is interactive in React — toggles, menus or form state. None of that survives here; the markup is the closed/default state and the handlers are gone. Re-wire them in your own framework.
  • Requires Tailwind, and the design tokens the classes reference (bg-card, text-muted-foreground, and so on). The template ZIPs ship a globals.css that defines them.

What each framework gets across the whole catalog — effects convert properly; this rung is markup.

For AI

The component, its props, the design tokens it expects and the command that installs it — as one prompt. Paste it into Claude, Cursor, v0 or ChatGPT and what they build around it will match the rest of the catalog instead of inventing its own system.

See the prompt

Used in these pages

Want the whole screen instead of this one section? Open a page and copy it entire.

9 more blocks in Command & Search

All of them free to read, copy and install — no account, no locked tiles, no watermarked preview. The whole catalog is open, and so are the API and the CLI.

Browse Command & Search

Shipping one commercially

Copying the code is free. Putting it in client work or a paid product is what Pro is for — the licence, not the access.

  • A commercial licence for everything in the catalog
  • Unlimited bundle exports, in Vue, Svelte and Tailwind
  • One payment — no subscription, nothing to renew
Pro — $79 once

More Command & Search blocks

View category
Open the full page for this block

Command Palette

The ⌘K switcher done properly: focus stays in the input while aria-activedescendant moves, arrows wrap, and the highlight resets on every query change.

Command & Search280 lines1 dep

Grouped Search Results

Results grouped by section with visible breadcrumb paths and <mark>-highlighted matches — users recognise where a result lives faster than they read its snippet.

Command & Search194 lines1 dep
Open the full page for this block

Keyboard Shortcuts Sheet

The "?" overlay, with chords written once in one notation and rendered per platform — mod becomes Command on Apple and Ctrl everywhere else, decided after mount so the markup never mismatches.

Command & Search252 lines1 dep
Open the full page for this block

Applied Filters Bar

The strip above a result set that answers "why am I only seeing four things" — every active constraint as a removable chip, with the excluded count beside it.

Command & Search238 lines1 dep
Open the full page for this block

Faceted Refinement Panel

Faceted search with result counts on every option, zero-count options kept visible and disabled so the list stays stable, and a note explaining why the counts do not sum.

Command & Search276 lines1 dep

Search Scope Switcher

One query counted across every scope it could have matched, as a real tablist with arrow-key movement — so an answer that is nowhere is visible without opening four tabs.

Command & Search247 lines1 dep
Open the full page for this block

Recent Search List

The empty state of a search box, filled with the searches that are worth repeating and the ones worth saving.

Command & Search150 linesNo deps
Open the full page for this block

Faceted Search Results

The whole faceted search assembled - rail, chips, live count and sort - with the intersection actually applied and relevance offered only when there is a query.

Command & Search388 lines1 dep
Open the full page for this block

Range Facet with Histogram

The facet that is a number: a distribution over a dual-thumb slider built from two real range inputs, with typed bounds clamped on blur rather than per keystroke.

Command & Search272 lines1 dep