Skip to content
View as Markdown

Autocomplete ​

The Autocomplete component provides a free-text input with a suggestion list. Unlike Select and Combobox, the component value is the raw input string — not a discrete item selection. For async suggestions use Autocomplete.Async. For custom compositions use Autocomplete.Parts.

Import ​

tsx
import { Autocomplete } from "@tailor-platform/app-shell";

The runnable examples also import useRef and useState from react, and Button, Field, Form, Text, and the AutocompleteAsyncFetcher type from @tailor-platform/app-shell.

Basic Usage ​

tsx
function BasicUsage() {
  return (
    <Autocomplete
      items={["Apple", "Banana", "Cherry"]}
      placeholder="Type a fruit..."
      onValueChange={(value) => console.log(value)}
    />
  );
}

Props ​

Autocomplete Props ​

PropTypeDefaultDescription
itemsI[]-Suggestion items. May be a flat array or an array of ItemGroup<T>
placeholderstring-Placeholder text for the input
emptyTextstring"No results."Text shown when no items match
valuestring-Controlled value (raw input string)
defaultValuestring-Initial value (uncontrolled)
onValueChange(value: string) => void-Called when the value changes
mapItem(item: T) => MappedItem-Map each item to its label, key, and optional custom render
classNamestring-Additional CSS classes for the root container
disabledbooleanfalseDisables the autocomplete
aria-labelstring-Accessible name for the input. Use when there is no visible label
aria-labelledbystring-ID of the element(s) that label the input
idstring-ID applied to the combobox input element

MappedItem ​

ts
interface MappedItem {
  label: string; // Display text, used for filtering and a11y
  key?: string; // React key. Defaults to label
  render?: React.ReactNode; // Custom JSX to render in the dropdown
}

ItemGroup ​

ts
interface ItemGroup<T> {
  label: string;
  items: T[];
}

Grouped Suggestions ​

tsx
function GroupedSuggestions() {
  const cities = [
    { label: "Japan", items: ["Tokyo", "Osaka", "Kyoto"] },
    { label: "France", items: ["Paris", "Lyon", "Marseille"] },
  ];

  return (
    <Autocomplete items={cities} aria-label="Grouped city search" placeholder="Search cities..." />
  );
}

Object Items with mapItem ​

When items are objects, use mapItem to tell the component how to display them. The selected value is the item's label string returned by mapItem:

tsx
function ObjectItems() {
  type City = { code: string; name: string };
  const cities: City[] = [
    { code: "TYO", name: "Tokyo" },
    { code: "OSA", name: "Osaka" },
  ];

  return (
    <Autocomplete
      items={cities}
      mapItem={(city) => ({ label: city.name, key: city.code })}
      aria-label="City name"
      placeholder="Search cities..."
      onValueChange={(name) => console.log(name)}
    />
  );
}

Async Suggestions ​

Use Autocomplete.Async to fetch suggestions as the user types. The fetcher is called on each keystroke (debounced). When the dropdown first opens or the input is cleared, the fetcher receives null as the query — return initial/default suggestions for null, or return an empty array to show nothing until the user starts typing.

Type ap or ba to try debounced lookups, a short loading state, and suggestion selection. The example filters local fixtures after a delay and checks the supplied AbortSignal; no network request is made. Its value remains the input text, including text that does not match a suggestion. In an application, replace the fixture lookup with your API and forward signal to fetch.

tsx
function AsyncSuggestions() {
  const [value, setValue] = useState("");
  const fetcher: AutocompleteAsyncFetcher<string> = async (query, { signal }) => {
    await new Promise((resolve) => setTimeout(resolve, 450));
    signal.throwIfAborted();
    return ["Apple", "Apricot", "Banana", "Cherry"].filter((fruit) =>
      fruit.toLowerCase().includes((query ?? "").toLowerCase()),
    );
  };

  return (
    <div className="max-w-sm space-y-3">
      <Autocomplete.Async
        aria-label="Async fruit suggestions"
        fetcher={fetcher}
        value={value}
        onValueChange={setValue}
        placeholder="Type ap or ba..."
        loadingText="Finding fruit..."
        emptyText="No matching fruit."
      />
      <Text.p role="status">Current text: {value || "Empty"}</Text.p>
    </div>
  );
}

Autocomplete.Async Props ​

Accepts all the same props as Autocomplete except items, plus:

PropTypeDefaultDescription
fetcherAutocompleteAsyncFetcher<T>-Fetcher called on each keystroke (debounced by default)
loadingTextstring"Loading..."Text shown while loading
errorTextstring"Couldn't load results."Message shown in the popover when the fetcher fails (with Retry)
retryTextstring"Retry"Label for the retry button in the error state
onFetchError(error: unknown) => void-Called once per outage when a fetch fails (logging/error tracking)

AutocompleteAsyncFetcher ​

ts
type AutocompleteAsyncFetcher<T> =
  | ((query: string | null, options: { signal: AbortSignal }) => Promise<T[]>)
  | {
      fn: (query: string | null, options: { signal: AbortSignal }) => Promise<T[]>;
      debounceMs: number;
    };

query is null when the user has not typed anything (e.g. the dropdown was just opened or the input was cleared). Pass { fn, debounceMs } to customize the debounce delay.

Error handling ​

If the fetcher throws or rejects, Autocomplete.Async renders a built-in inline error state in the popover — the errorText message plus a Retry button that re-runs the last fetch — instead of the misleading "No results." empty state. Aborted/superseded requests are ignored, and announcements are de-duped per outage. Pass onFetchError to run a side effect (logging, toast) — it fires once per outage and re-arms after the next successful fetch.

Low-level Primitives ​

Autocomplete.Parts exposes styled sub-components and hooks for fully custom compositions:

tsx
const {
  Root,
  Value,
  InputGroup,
  Input,
  Trigger,
  Content,
  List,
  Item,
  Empty,
  Clear,
  Group,
  GroupLabel,
  Collection,
  Status,
} = Autocomplete.Parts;

Form submission ​

Inside a Field.Root, the field's name identifies the value and these props are unnecessary — see Form. They matter for native submission: a plain <form>, new FormData(form), or a server action.

PropTypeDefaultDescription
namestring-Names the input for native submission. Ignored inside a Field.Root — the field's name wins.
formstring-id of the owning form, when the control is rendered outside it.
requiredbooleanfalseBlocks submission until a value is chosen, surfacing the matching Field.Error.
inputRefReact.Ref<HTMLInputElement>-Ref to the underlying text input (use for React Hook Form's field.ref).

Autocomplete's value is the raw input string, so no value-serialisation hook is needed.

Examples ​

Controlled Autocomplete ​

tsx
const [query, setQuery] = useState("");

<Autocomplete items={suggestions} value={query} onValueChange={setQuery} placeholder="Search..." />;

Address Input with Async Suggestions ​

Type Maple or Oak, choose a suggestion, and submit to inspect the address. You may also submit your own free text: Autocomplete does not require choosing an existing item. An empty address is blocked by the surrounding Field and Form. Suggestions and submission are local-only.

tsx
function AddressSuggestions() {
  const [submitted, setSubmitted] = useState<{ address: string } | null>(null);
  const fetcher: AutocompleteAsyncFetcher<string> = async (query, { signal }) => {
    await new Promise((resolve) => setTimeout(resolve, 450));
    signal.throwIfAborted();
    if (!query) return [];
    return ["10 Maple Street", "12 Maple Avenue", "20 Oak Road"].filter((address) =>
      address.toLowerCase().includes(query.toLowerCase()),
    );
  };

  return (
    <Form<{ address: string }>
      noValidate
      onFormSubmit={setSubmitted}
      className="max-w-sm space-y-3"
    >
      <Field.Root name="address">
        <Field.Label>Shipping address</Field.Label>
        <Autocomplete.Async fetcher={fetcher} placeholder="Type Maple or Oak..." required />
        <Field.Description>Choose a suggestion or enter your own address.</Field.Description>
        <Field.Error match="valueMissing">Enter an address.</Field.Error>
      </Field.Root>
      <Button type="submit">Use address</Button>
      <Text.p role="status">Submitted address: {submitted?.address ?? "None"}</Text.p>
    </Form>
  );
}

Async with Parts (custom composition) ​

Combine Autocomplete.useAsync with Autocomplete.Parts for full control over layout and rendering:

Autocomplete.useAsync accepts the same options as Autocomplete.Async (including onFetchError) and returns:

PropertyTypeDescription
itemsT[]Currently loaded items
loadingbooleanWhether a fetch is in progress
errorunknownThe error thrown by the last fetch, if any
retry() => voidRe-runs the last fetch (use to build a custom retry UI)

Type k or to to start a lookup. The first completed request deliberately fails; Retry city search retries the same query and succeeds. Later searches work normally. The custom composition shows loading, an error, Retry, empty results, and the current input text without a backend. filter={null} prevents a second filtering pass over the already-filtered results.

tsx
function AsyncWithParts() {
  const failNext = useRef(true);
  const suggestions = Autocomplete.useAsync<string>({
    fetcher: async (query, { signal }) => {
      await new Promise((resolve) => setTimeout(resolve, 450));
      signal.throwIfAborted();
      if (failNext.current) {
        failNext.current = false;
        throw new Error("Simulated lookup failure");
      }
      return ["Tokyo", "Osaka", "Kyoto", "Kobe"].filter((city) =>
        city.toLowerCase().includes((query ?? "").toLowerCase()),
      );
    },
  });

  return (
    <div className="max-w-sm space-y-3">
      <Text.p>The first lookup fails locally. Retry the same search to recover.</Text.p>
      <Autocomplete.Parts.Root
        items={suggestions.items}
        value={suggestions.value}
        onValueChange={suggestions.onValueChange}
        filter={null}
      >
        <Autocomplete.Parts.InputGroup>
          <Autocomplete.Parts.Input
            aria-label="Custom async city search"
            placeholder="Type k or to..."
          />
          <Autocomplete.Parts.Clear />
          <Autocomplete.Parts.Trigger />
        </Autocomplete.Parts.InputGroup>
        <Autocomplete.Parts.Content>
          <Autocomplete.Parts.Empty>
            {suggestions.loading ? (
              "Finding cities..."
            ) : suggestions.error ? (
              <div className="space-y-2">
                <Text.p>Could not load cities.</Text.p>
                <Button type="button" size="sm" variant="outline" onClick={suggestions.retry}>
                  Retry city search
                </Button>
              </div>
            ) : (
              "No matching cities."
            )}
          </Autocomplete.Parts.Empty>
          <Autocomplete.Parts.List>
            {(city: string) => (
              <Autocomplete.Parts.Item key={city} value={city}>
                {city}
              </Autocomplete.Parts.Item>
            )}
          </Autocomplete.Parts.List>
        </Autocomplete.Parts.Content>
      </Autocomplete.Parts.Root>
      <Text.p role="status">
        {suggestions.loading
          ? "Loading cities..."
          : suggestions.error
            ? "Lookup failed; retry is available."
            : `Current text: ${suggestions.value || "Empty"}`}
      </Text.p>
    </div>
  );
}

Accessibility ​

  • Input is keyboard accessible with arrow key navigation
  • Pressing Escape closes the suggestion list
  • Selecting a suggestion fills the input with the item's label
  • When used standalone (no visible <label>), give the input an accessible name with aria-label or aria-labelledby — otherwise screen readers announce only the current value:
tsx
function AccessibleName() {
  return <Autocomplete items={["Tokyo", "Osaka", "Kyoto"]} aria-label="City search" />;
}
  • Select - Non-searchable discrete item selection
  • Combobox - Searchable combobox that returns discrete items
  • Input - Plain text input without suggestions