> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Autocomplete

> Shows search results as users type their query in a search box.

export const Index = () => <Tooltip tip="An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.">
    index
  </Tooltip>;

export const customLabel_0 = undefined

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="m6 9 6 6 6-6" />
          </svg>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="react"
    baseHref="/doc/api-reference/widgets/autocomplete"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
{ value: "vue", label: "Vue", description: "Vue InstantSearch" },
]}
  />
</div>

<Callout icon="flask-conical" color="#14b8a6">
  This widget is **{customLabel_0 || "experimental"}** and is subject to change in minor versions.
</Callout>

<Note>
  This is the **React InstantSearch v7** documentation.
  If you're upgrading from v6, see the [upgrade guide](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-v6-to-react-instantsearch-v7).
  If you were using React InstantSearch Hooks,
  this v7 documentation applies—just check for [necessary changes](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-hooks-to-react-instantsearch-v7).
  To continue using v6, you can find the [archived documentation](https://algolia.com/old-docs/deprecated/instantsearch/react/v6/api-reference/instantsearch/).
</Note>

```tsx Signature theme={"system"}
<EXPERIMENTAL_Autocomplete
  indices={array}
  feeds={array}
  showQuerySuggestions={object}
  showPromptSuggestions={object}
  showRecent={boolean | object}
  transformItems={function}
  onSelect={function}
  getSearchPageURL={function}
  searchParameters={object}
  panelComponent={function}
  classNames={object}
  placeholder={string}
  autoFocus={boolean}
  detachedMediaQuery={string}
  translations={object}
  aiMode={boolean}
  requiresSearch={boolean}
/>
```

## Import

```jsx JavaScript icon=code theme={"system"}
import { EXPERIMENTAL_Autocomplete } from "react-instantsearch";
```

## About this widget

`<Autocomplete>` is one of the most common widgets in a search UI.
With this widget, users can get search results as they type their query.

This widget includes a `showQuerySuggestions` feature that displays query suggestions from a separate <Index />.

<Note>
  The widget defers registering and querying its indices until the user first focuses the search input.
  This avoids unnecessary network requests on page load.
  When [`autoFocus`](#param-autofocus) is enabled, the input is focused on load, so the indices are registered immediately.
</Note>

## Examples

```jsx JavaScript icon=code theme={"system"}
import React from "react";
import { liteClient as algoliasearch } from "algoliasearch/lite";
import { InstantSearch, Autocomplete } from "react-instantsearch";

const searchClient = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <EXPERIMENTAL_Autocomplete
        indices={[
          {
            indexName: "instant_search",
            getQuery: (item) => item.name,
            getURL: (item) => `/search?q=${item.name}`,
            headerComponent: () => <div>Products</div>,
            itemComponent: ({ item, onSelect }) =>
              <div onClick={onSelect}>{item.name}</div>,
          },
        ]}
        showQuerySuggestions={{
          indexName: "query_suggestions",
        }}
      />
    </InstantSearch>
  );
}
```

## Props

<ParamField body="indices" type="array">
  An array of objects that define the indices to query and how to display the results.
  Use either `indices` or [`feeds`](#param-feeds).

  * `indexName`: the name of the index to query
  * `getQuery`: preprocess the query before it is sent for search
  * `getURL`: update the URL to send the search request
  * `searchParameters`: additional [search parameters](/doc/api-reference/api-parameters/) to send with the search request
  * `headerComponent`: component to render for the header of the index
  * `itemComponent`: component to render for each result from a query
  * `noResultsComponent`: component to render when no results are found for the index
  * `classNames`: CSS classes to customize the appearance.
    * `root`: the index section root element.
    * `list`: the list of results.
    * `header`: the section header.
    * `item`: each result item.
    * `noResults`: the no results element.

  ```js JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    indices={[
      {
        indexName: "instant_search",
        getQuery: (query) => query,
        getURL: (item) => `/search/?q=${item.query}`,
        searchParameters: {
          hitsPerPage: 5,
        },
        headerComponent: ({ items }) =>
          <div>Products ({items.length} results)</div>,
        itemComponent: ({ item, onSelect }) =>
          <div onClick={onSelect}>{item.name}</div>,
        noResultsComponent: () =>
          <div>No results found. Try a different query.</div>,
      },
    ]}
  />
  ```
</ParamField>

<ParamField body="feeds" type="array">
  An array of feed configurations that populate the panel from a single [multifeed composition](/doc/guides/compositions/multifeed-compositions) response instead of querying separate `indices`.
  Use `feeds` to display several result sets that come from one composition.

  The `feeds` and `indices` props are mutually exclusive.
  To use `feeds`, you need a composition-based `<InstantSearch>` (the `compositionID` prop must be set). See the [`Feeds`](/doc/api-reference/widgets/feeds/react) widget for the standalone equivalent.

  Each feed configuration supports these properties:

  * `feedID`: the ID of the feed in the composition response. Each `feedID` must be unique, including feed IDs used in `showQuerySuggestions` and `showPromptSuggestions`.
  * `getQuery`: preprocess the query before it is sent for search.
  * `getURL`: update the URL to send the search request.
  * `headerComponent`: component to render for the header of the feed.
  * `itemComponent`: component to render for each result in the feed.
  * `noResultsComponent`: component to render when the feed returns no results.
  * `classNames`: CSS classes to customize the appearance.
    * `root`: the feed section root element.
    * `list`: the list of results.
    * `header`: the section header.
    * `item`: each result item.
    * `noResults`: the no results element.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    feeds={[
      {
        feedID: "products",
        getQuery: (item) => item.name,
        getURL: (item) => `/search?q=${item.name}`,
        headerComponent: ({ items }) =>
          <div>Products ({items.length} results)</div>,
        itemComponent: ({ item, onSelect }) =>
          <div onClick={onSelect}>{item.name}</div>,
        noResultsComponent: () =>
          <div>No results found. Try a different query.</div>,
      },
    ]}
  />
  ```
</ParamField>

<ParamField body="showQuerySuggestions" type="object">
  Configures the query suggestions feature.

  When `feeds` is set, reference the suggestions feed with `feedID` instead of `indexName`.

  * `indexName`: the name of the index to query for suggestions.
  * `feedID`: the ID of the suggestions feed in the composition response. Use this property when `feeds` is set. It replaces `indexName`.
  * `getURL`: update the URL to send the search request.
  * `headerComponent`: component to render for the header of the index.
  * `itemComponent`: component to render for each suggestion.
  * `classNames`: CSS classes to customize the appearance.
    * `root`: the index section root element.
    * `list`: the list of results.
    * `header`: the section header.
    * `item`: each result item.
    * `noResults`: the no results element.

  ```js JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    showQuerySuggestions={{
      indexName: "query_suggestions",
      getURL: (item) => `/search?q=${item.query}`,
      headerComponent: ({ items }) =>
        <div>Suggestions ({items.length} results)</div>,
      itemComponent: ({ item, onSelect }) =>
        <div onClick={onSelect}>{item.query}</div>,
    }}
  />
  ```
</ParamField>

<ParamField body="showPromptSuggestions" type="object">
  Configures the prompt suggestions feature.
  Shows prompt suggestions from a separate <Index />.
  When users select a suggestion,
  it's sent to a [Chat](/doc/api-reference/widgets/chat/react) widget in the same index.

  When `feeds` is set, reference the prompt suggestions feed with `feedID` instead of `indexName`.

  * `indexName`: the name of the index to query for prompt suggestions.
  * `feedID`: the ID of the suggestions feed in the composition response. Use this property when `feeds` is set. It replaces `indexName`.
  * `getURL`: a function that returns the URL to open when a user selects a prompt suggestion.
  * `headerComponent`: component to render for the header of the prompt suggestions.
  * `itemComponent`: component to render for each prompt suggestion (receives `item` with a `prompt` field and an optional `label` field, and `onSelect`).
  * `classNames`: CSS classes to customize the appearance.
    * `root`: the index section root element.
    * `list`: the list of results.
    * `header`: the section header.
    * `item`: each result item.
    * `noResults`: the no results element.
  * `searchParameters`: additional [search parameters](/doc/api-reference/api-parameters/) to send with the request when `indices` is set.

  <Note>
    To open the chat and send messages, `showPromptSuggestions` requires a `Chat` widget in the same index.
  </Note>

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    showPromptSuggestions={{
      indexName: "prompt_suggestions",
      headerComponent: ({ items }) => (
        <div>Ask me anything ({items.length} suggestions)</div>
      ),
      itemComponent: ({ item, onSelect }) => (
        <div onClick={onSelect}>{item.prompt}</div>
      ),
    }}
  />
  ```
</ParamField>

<ParamField body="showRecent" type="boolean | object">
  Configures the recent searches feature. Displays previously searched queries stored in local storage.

  When set to `true`, uses default settings. When set to an object, you can configure:

  * `storageKey`: the key to use in local storage (default: `ais.recentSearches`)
  * `headerComponent`: component to render for the header above the recent searches list
  * `itemComponent`: component to render for each recent search item (receives `item`, `onSelect`, and `onRemoveRecentSearch` props)
  * `classNames`: CSS classes to customize the appearance.
    * `root`: the index section root element.
    * `list`: the list of results.
    * `header`: the section header.
    * `item`: each result item.
    * `noResults`: the no results element.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    showRecent={true}
  />

  {/* With customization */}
  <EXPERIMENTAL_Autocomplete
    // ...
    showRecent={{
      storageKey: 'my-app-recent-searches',
      headerComponent: ({ items }) => (
        <div>Recent Searches</div>
      ),
      itemComponent: ({ item, onSelect, onRemoveRecentSearch }) => (
        <div>
          <button onClick={onSelect}>{item.query}</button>
          <button onClick={onRemoveRecentSearch}>×</button>
        </div>
      ),
    }}
  />
  ```
</ParamField>

<ParamField body="transformItems" type="function">
  Transforms the items before they are displayed. This function receives an array of index configurations with their hits and should return an array in the same format.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    transformItems={(indices) =>
      indices.map((index) => ({
        ...index,
        hits: index.hits.map((hit) => ({
          ...hit,
          _highlightResult: {
            ...hit._highlightResult,
            name: {
              ...hit._highlightResult.name,
              value: hit._highlightResult.name.value.toUpperCase(),
            },
          },
        })),
      }))
    }
  />
  ```
</ParamField>

<ParamField body="searchParameters" type="object">
  Additional [search parameters](/doc/api-reference/api-parameters/) to send with the search request for every index.

  ```js JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    searchParameters={{
      hitsPerPage: 5,
    }}
  />
  ```
</ParamField>

<ParamField body="onSelect" type="function">
  A function that is called when the user selects an item. If not provided, the default implementation:

  * navigates to the URL of an item if the index configuration defines `getURL()`;
  * or navigates to the URL of the search page if autocomplete is not in a search page and `getSearchPageURL()` is defined;
  * or otherwise refines the query

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    onSelect={({ query, setQuery, url }) => {
      if (inSearchPage && !url) {
        setQuery(query);
        return;
      }
      
      window.location.href = url || `/search?q=${query}`;
    }}
  />
  ```
</ParamField>

<ParamField body="getSearchPageURL" type="function">
  A function that returns the URL of the search page for a given search state.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    getSearchPageURL={(nextUiState) => {
      return `/search?q=${qs.stringify(nextUiState)}`;
    }}
  />
  ```
</ParamField>

<ParamField body="panelComponent" type="function">
  Use the component to customize how the panel is rendered.
  This is useful when implementing layouts with multiple rows or columns.

  The component receives a prop containing:

  * `elements`: a key-value dictionary of indices to render. These include regular index names, and special elements like `recent`, `suggestions`, and `promptSuggestions`, if applicable.
  * `indices`: an array containing the data for each index.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    panelComponent={({ elements, indices }) => (
      <div>
        <p>My custom panel</p>
        <div className="left">{elements.suggestions}</div>
        <div className="right">{elements.instant_search}</div>
      </div>
    )}
  />
  ```
</ParamField>

<ParamField body="classNames" type="object">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/react/#style-your-widgets)
  and pass to the widget's elements.
  It's useful to style widgets with class-based CSS frameworks like [Bootstrap](https://getbootstrap.com)
  or [Tailwind CSS](https://tailwindcss.com).

  **Root and detached shell:**

  * `root`: the widget's root element.
  * `detachedOverlay`: the detached overlay backdrop.
  * `detachedContainer`: the detached container.
  * `detachedFormContainer`: the detached form container.
  * `detachedSearchButton`: the detached search button.
  * `detachedSearchButtonIcon`: the detached search button icon wrapper.
  * `detachedSearchButtonSearchIcon`: the detached search button search icon.
  * `detachedSearchButtonPlaceholder`: the detached search button placeholder.
  * `detachedSearchButtonQuery`: the detached search button query.
  * `detachedSearchButtonClear`: the detached search button clear button.
  * `detachedSearchButtonClearIcon`: the detached search button clear icon.

  **Panel:**

  * `panel`: the panel root element.
  * `panelOpen`: the panel root element when open.
  * `panelLayout`: the panel layout element.

  **Search form:**

  * `form`: the search form.
  * `inputWrapperPrefix`: the input prefix area (contains submit button and loading indicator).
  * `backButton`: the back button (detached mode).
  * `backButtonIcon`: the back button icon.
  * `label`: the submit label.
  * `submitButton`: the submit button.
  * `submitButtonIcon`: the submit button icon.
  * `loadingIndicator`: the loading indicator.
  * `loadingIndicatorIcon`: the loading indicator icon.
  * `inputWrapper`: the input wrapper.
  * `input`: the search input.
  * `inputWrapperSuffix`: the input suffix area (contains reset button and AI mode button).
  * `resetButton`: the reset/clear button.
  * `resetButtonIcon`: the reset/clear button icon.
  * `aiModeButton`: the AI mode button.
  * `aiModeButtonIcon`: the AI mode button icon.
  * `aiModeButtonLabel`: the AI mode button label.

  Each source (`indices`, `showQuerySuggestions`, `showPromptSuggestions`, `showRecent`) also accepts its own `classNames` for styling result items. See their respective options for details.

  ```js JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    classNames={{
      root: "MyCustomAutocomplete",
      form: "MyCustomAutocompleteForm",
      input: "MyCustomAutocompleteInput",
      submitButton: "MyCustomAutocompleteSubmit",
      resetButton: "MyCustomAutocompleteReset",
      panel: "MyCustomAutocompletePanel",
    }}
  />
  ```
</ParamField>

<ParamField body="placeholder" type="string">
  Placeholder text for the search input.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    placeholder="Search for products..."
  />
  ```
</ParamField>

<ParamField body="autoFocus" type="boolean" default="false">
  Whether to focus the input and open the panel by default.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    autoFocus={true}
  />
  ```
</ParamField>

<ParamField body="detachedMediaQuery" type="string" default="(max-width: 680px)">
  Media query to enable detached (mobile) mode. When the media query matches, the autocomplete switches to a full-screen overlay with a modal interface optimized for mobile devices. In detached mode, the search form shows a back button (`.ais-AutocompleteBackButton`) to close the overlay.

  Set to an empty string to disable detached mode. When omitted, it defaults to the CSS variable `--ais-autocomplete-detached-media-query`, or `"(max-width: 680px)"` if the variable is not set.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    detachedMediaQuery="(max-width: 768px)"
  />

  {/* Disable detached mode */}
  <EXPERIMENTAL_Autocomplete
    // ...
    detachedMediaQuery=""
  />
  ```
</ParamField>

<ParamField body="translations" type="object">
  Text labels for detached mode controls.

  * `detachedCancelButtonText`: label for the detached cancel button.
  * `detachedSearchButtonTitle`: title for the detached search button.
  * `detachedClearButtonTitle`: title for the detached clear button.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    translations={{
      detachedCancelButtonText: "Close",
      detachedSearchButtonTitle: "Search",
      detachedClearButtonTitle: "Reset",
    }}
  />
  ```
</ParamField>

<ParamField body="aiMode" type="boolean" default="false">
  Whether to show an AI Mode button in the search input.
  When users click this button, it opens the [Chat](/doc/api-reference/widgets/chat/react) widget and sends the current query.

  To use this prop, add a `<Chat>` widget on the same index.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    aiMode={true}
  />
  ```
</ParamField>

<ParamField body="requiresSearch" type="boolean" default={true}>
  Whether the widget makes InstantSearch require a main search request.
  By default (`true`), the widget contributes to the main search.
  Set it to `false` to opt the widget out of the main search: if it's the only widget on the page, no main search request is sent.

  ```jsx JavaScript icon=code theme={"system"}
  <EXPERIMENTAL_Autocomplete
    // ...
    requiresSearch={false}
  />
  ```
</ParamField>
