> ## 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

> This function creates an autocomplete experience and attaches it to an element of the DOM.

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>;

<Tip>
  Autocomplete is also available as an experimental widget in InstantSearch,
  making it easier to integrate into your search experience.
  For more information,
  see the API reference for [InstantSearch.js](/doc/api-reference/widgets/autocomplete/js) or
  [React InstantSearch](/doc/api-reference/widgets/autocomplete/react).
</Tip>

By default, it uses [Preact 10](https://preactjs.com/guide/v10/whats-new/) to render templates.

## Installation

First, you need to install the package.

<CodeGroup>
  ```sh npm theme={"system"}
  npm install @algolia/autocomplete-js
  ```

  ```sh yarn theme={"system"}
  yarn add @algolia/autocomplete-js
  ```
</CodeGroup>

Then import it in your project:

```js JavaScript icon=code theme={"system"}
import { autocomplete } from "@algolia/autocomplete-js";
```

If you don't use a package manager, you can use the HTML `script` element:

```html HTML icon=code-xml theme={"system"}
<script
  src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-js@1.19.9/dist/umd/index.production.js"
  integrity="sha256-wpkAnzdLcIepcHpyULu6SUAwGne9BupLbkv+uv/SUeI="
  crossorigin="anonymous"
>
</script>
<script>
  const { autocomplete } = window["@algolia/autocomplete-js"];
</script>
```

## Example

Make sure to define an empty container in your HTML where to inject your autocomplete.

```js JavaScript icon=code theme={"system"}
<div id="autocomplete"></div>
```

This example uses Autocomplete with an Algolia <Index />,
along with the [`algoliasearch`](https://www.npmjs.com/package/algoliasearch) API client.
All Algolia utility functions to retrieve hits and parse results are available directly in the package.

<CodeGroup>
  ```js JavaScript theme={"system"}
  import { liteClient as algoliasearch } from "algoliasearch/lite";
  import { autocomplete, getAlgoliaResults } from "@algolia/autocomplete-js";

  const searchClient = algoliasearch(
    "latency",
    "6be0576ff61c053d5f9a3225e2a90f76",
  );

  const autocompleteSearch = autocomplete({
    container: "#autocomplete",
    getSources() {
      return [
        {
          sourceId: "querySuggestions",
          getItemInputValue: ({ item }) => item.query,
          getItems({ query }) {
            return getAlgoliaResults({
              searchClient,
              queries: [
                {
                  indexName: "instant_search_demo_query_suggestions",
                  params: {
                    query,
                    hitsPerPage: 4,
                  },
                },
              ],
            });
          },
          templates: {
            item({ item, components }) {
              return components.ReverseHighlight({
                hit: item,
                attribute: "query",
              });
            },
          },
        },
      ];
    },
  });
  ```

  ```jsx JSX theme={"system"}
  import { liteClient as algoliasearch } from "algoliasearch/lite";
  import { autocomplete, getAlgoliaResults } from "@algolia/autocomplete-js";

  const searchClient = algoliasearch(
    "latency",
    "6be0576ff61c053d5f9a3225e2a90f76",
  );

  const autocompleteSearch = autocomplete({
    container: "#autocomplete",
    getSources() {
      return [
        {
          sourceId: "querySuggestions",
          getItemInputValue: ({ item }) => item.query,
          getItems({ query }) {
            return getAlgoliaResults({
              searchClient,
              queries: [
                {
                  indexName: "instant_search_demo_query_suggestions",
                  params: {
                    query,
                    hitsPerPage: 4,
                  },
                },
              ],
            });
          },
          templates: {
            item({ item, components }) {
              return <components.ReverseHighlight hit={item} attribute="query" />;
            },
          },
        },
      ];
    },
  });
  ```
</CodeGroup>

## Parameters

<ParamField body="container" type="string | HTMLElement" required>
  The container for the Autocomplete search box.
  You can either pass a [CSS selector](https://developer.mozilla.org/docs/Web/CSS/CSS_Selectors)
  or an [Element](https://developer.mozilla.org/docs/Web/API/HTMLElement).
  If there are several containers matching the selector,
  Autocomplete picks up the first one.
</ParamField>

<ParamField body="panelContainer" type="string | HTMLElement">
  The container for the Autocomplete panel.
  You can either pass a [CSS selector](https://developer.mozilla.org/docs/Web/CSS/CSS_Selectors)
  or an [Element](https://developer.mozilla.org/docs/Web/API/HTMLElement).
  If there are several containers matching the selector,
  Autocomplete picks up the first one.
</ParamField>

<ParamField body="panelPlacement" type="&#x22;start&#x22; | &#x22;end&#x22; | &#x22;full-width&#x22; | &#x22;input-wrapper-width&#x22;" default="input-wrapper-width">
  The panel's horizontal position.
</ParamField>

<ParamField body="insights" type="boolean | InsightsPluginOptions" default={false}>
  Whether to enable the [Algolia Insights plugin](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin).

  This option accepts an object to configure the plugin.
  You can see the available options in the [plugin's documentation](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin#parameters).

  If you don't pass an `insightsClient`,
  it will be automatically detected from the `window` object,
  or downloaded from the [jsDelivr CDN](https://www.jsdelivr.com/).

  If you manually enable the Insights plugin, this option won't have any effect.
</ParamField>

<ParamField body="translations" type="Translations">
  ```ts Type definition theme={"system"}
  type Translations = Partial<{
    clearButtonTitle: string; // defaults to 'Clear'
    detachedCancelButtonText: string; // defaults to 'Cancel'
    submitButtonTitle: string; // defaults to 'Submit'
  }>
  ```

  A dictionary of translations to support internationalization.
</ParamField>

<ParamField body="classNames" type="ClassNames">
  Class names to inject for each created DOM element.
  This is useful to style your autocomplete with external CSS frameworks.

  ```ts Type definition theme={"system"}
  type ClassNames = Partial<{
    detachedCancelButton: string;
    detachedFormContainer: string;
    detachedContainer: string;
    detachedOverlay: string;
    detachedSearchButton: string;
    detachedSearchButtonIcon: string;
    detachedSearchButtonPlaceholder: string;
    form: string;
    input: string;
    inputWrapper: string;
    inputWrapperPrefix: string;
    inputWrapperSuffix: string;
    item: string;
    label: string;
    list: string;
    loadingIndicator: string;
    panel: string;
    panelLayout: string;
    clearButton: string;
    root: string;
    source: string;
    sourceFooter: string;
    sourceHeader: string;
    submitButton: string;
  }>;
  ```
</ParamField>

<ParamField body="components">
  [Components](#components) to register in the Autocomplete rendering lifecycles.
  Registered components become available in [`templates`](/doc/ui-libraries/autocomplete/core-concepts/templates),
  [`render`](#param-render),
  and in [`renderNoResults`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-render-no-results).

  <CodeGroup>
    ```js JavaScript theme={"system"}
    import { MyComponent } from "./my-components";

    autocomplete({
      // ...
      components: {
        MyComponent,
      },
      render({ sections, components, html, render }, root) {
        render(
          html`<div class="aa-PanelLayout aa-Panel--scollable">${sections}</div>
            ${components.MyComponent()}`,
          root,
        );
      },
    });
    ```

    ```jsx JSX theme={"system"}
    import { render } from "preact";
    import { MyComponent } from "./my-components";

    autocomplete({
      // ...
      components: {
        MyComponent,
      },
      render({ sections, components }, root) {
        render(
          <Fragment>
            <div className="aa-PanelLayout aa-Panel--scollable">{sections}</div>
            <components.MyComponent />
          </Fragment>,
          root,
        );
      },
    });
    ```
  </CodeGroup>

  [Four components](https://github.com/algolia/autocomplete/tree/next/packages/autocomplete-js/src/components) are registered by default:

  * [`Highlight`](#highlight) to highlight matches in Algolia results.
  * [`Snippet`](#snippet) to snippet matches in Algolia results.
  * [`ReverseHighlight`](#reversehighlight) to reverse highlight matches in Algolia results.
  * [`ReverseSnippet`](#reversesnippet) to reverse highlight and snippet matches in Algolia results.

  <CodeGroup>
    ```js JavaScript theme={"system"}
    autocomplete({
      // ...
      getSources({ query }) {
        return [
          {
            getItems() {
              return [
                // ...
              ];
            },
            templates: {
              item({ item, components }) {
                return components.Highlight({ hit: item, attribute: "name" });
              },
            },
          },
        ];
      },
    });
    ```

    ```jsx JSX theme={"system"}
    autocomplete({
      // ...
      getSources({ query }) {
        return [
          {
            getItems() {
              return [
                // ...
              ];
            },
            templates: {
              item({ item, components }) {
                return <components.Highlight hit={item} attribute="name" />;
              },
            },
          },
        ];
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="render" type="function">
  ```ts Type definition theme={"system"}
  (params: {
    children: VNode,
    elements: Elements,
    sections: VNode[],
    state: AutocompleteState<TItem>,
    createElement: Pragma,
    Fragment: PragmaFrag,
    render: Render,
    html: HTMLTemplate,
  }) => void
  ```

  The function that renders the autocomplete panel.
  This is useful to customize the rendering,
  for example, using multi-row or multi-column layouts.

  This is the default implementation:

  ```js JavaScript icon=code theme={"system"}
  autocomplete({
    // ...
    render({ children, render }, root) {
      render(children, root);
    },
  });
  ```

  You can use `sections`, which holds the components tree of your autocomplete,
  to customize the wrapping layout.

  <CodeGroup>
    ```js JavaScript theme={"system"}
    autocomplete({
      // ...
      render({ sections, render, html }, root) {
        render(
          html`<div class="aa-PanelLayout aa-Panel--scrollable">${sections}</div>`,
          root,
        );
      },
    });
    ```

    ```jsx JSX theme={"system"}
    import { h } from "preact";

    autocomplete({
      // ...
      render({ sections, render }, root) {
        render(
          <div className="aa-PanelLayout aa-Panel--scrollable">{sections}</div>,
          root,
        );
      },
    });
    ```
  </CodeGroup>

  If you need to split the content across a more complex layout,
  you can use `elements` instead to pick which source to display based on its [`sourceId`](/doc/ui-libraries/autocomplete/core-concepts/sources#param-source-id).

  <CodeGroup>
    ```js JavaScript theme={"system"}
    import { createQuerySuggestionsPlugin } from "@algolia/autocomplete-plugin-query-suggestions";
    import { createLocalStorageRecentSearchesPlugin } from "@algolia/autocomplete-plugin-recent-searches";
    import algoliasearch from "algoliasearch";

    const searchClient = algoliasearch(
      "latency",
      "6be0576ff61c053d5f9a3225e2a90f76",
    );
    const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
      key: "search",
    });
    const querySuggestionsPlugin = createQuerySuggestionsPlugin({
      searchClient,
      indexName: "instant_search_demo_query_suggestions",
    });

    autocomplete({
      // ...
      plugins: [recentSearchesPlugin, querySuggestionsPlugin],
      getSources({ query }) {
        return [
          {
            sourceId: "products",
            // ...
          },
        ];
      },
      render({ elements, render, html }, root) {
        const { recentSearchesPlugin, querySuggestionsPlugin, products } = elements;

        render(
          html`<div class="aa-PanelLayout aa-Panel--scrollable">
            <div>${recentSearchesPlugin} ${querySuggestionsPlugin}</div>
            <div>${products}</div>
          </div>`,
          root,
        );
      },
    });
    ```

    ```jsx JSX theme={"system"}
    import { createQuerySuggestionsPlugin } from "@algolia/autocomplete-plugin-query-suggestions";
    import { createLocalStorageRecentSearchesPlugin } from "@algolia/autocomplete-plugin-recent-searches";
    import algoliasearch from "algoliasearch";
    import { h } from "preact";

    const searchClient = algoliasearch(
      "latency",
      "6be0576ff61c053d5f9a3225e2a90f76",
    );
    const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
      key: "search",
    });
    const querySuggestionsPlugin = createQuerySuggestionsPlugin({
      searchClient,
      indexName: "instant_search_demo_query_suggestions",
    });

    autocomplete({
      // ...
      plugins: [recentSearchesPlugin, querySuggestionsPlugin],
      getSources({ query }) {
        return [
          {
            sourceId: "products",
            // ...
          },
        ];
      },
      render({ elements, render }, root) {
        const { recentSearchesPlugin, querySuggestionsPlugin, products } = elements;

        render(
          <div className="aa-PanelLayout aa-Panel--scrollable">
            <div>
              {recentSearchesPlugin}
              {querySuggestionsPlugin}
            </div>
            <div>{products}</div>
          </div>,
          root,
        );
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="renderNoResults" type="function">
  ```ts Type definition theme={"system"}
  (params: {
    children: VNode,
    state: AutocompleteState<TItem>,
    sections: VNode[],
    createElement: Pragma,
    Fragment: PragmaFrag,
    render: Render,
    html: HTMLTemplate,
  }) => void
  ```

  The function that renders a no results section when there are no hits.
  This is useful to let users know that the query returned no results.

  There's no default implementation.
  By default, Autocomplete closes the panel when there's no results.
  Here's how you can customize this behavior:

  ```js JavaScript icon=code theme={"system"}
  autocomplete({
    // ...
    renderNoResults({ state, render }, root) {
      render(`No results for "${state.query}".`, root);
    },
  });
  ```
</ParamField>

<ParamField body="renderer">
  The virtual DOM implementation to plug to Autocomplete.
  It defaults to Preact.

  <Expandable title="properties">
    <ParamField body="renderer.createElement" type="function" post={["default: preact.createElement"]}>
      ```ts Type definition theme={"system"}
      (type: any, props: Record<string, any> | null, ...children: ComponentChildren[]) => VNode
      ```

      The function that create virtual nodes.

      The default is Preact 10's `createElement`.
    </ParamField>

    <ParamField body="renderer.Fragment" type="PragmaFrag" post={["default: preact.Fragment"]}>
      The component to use to create fragments.

      The default is Preact 10's `Fragment`.
    </ParamField>

    <ParamField body="renderer.render" type="Render" post={["default: preact.render"]}>
      The function to render a tree of VNodes into a DOM container.

      The default is Preact 10's `render`.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="detachedMediaQuery" type="string" default="(max-width: 680px)">
  The detached mode turns the dropdown display into a full screen, modal experience.

  For more information, see [Detached mode](/doc/ui-libraries/autocomplete/core-concepts/detached-mode).
</ParamField>

The `autocomplete` function also accepts all the props that [`createAutocomplete`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-core/createAutocomplete#parameters) supports:

<ParamField body="getSources">
  The [sources](/doc/ui-libraries/autocomplete/core-concepts/sources) to get the collections from.
</ParamField>

<ParamField body="reshape" type="Reshape">
  The function called to reshape the sources after they're resolved.

  This is useful to transform sources before rendering them.
  You can group sources by attribute, remove duplicates, create shared limits between sources, etc.

  See [Reshaping sources](/doc/ui-libraries/autocomplete/guides/reshaping-sources) for more information.

  ```ts TypeScript icon="code" theme={"system"}
  type Reshape = (params: {
    sources: AutocompleteReshapeSource[];
    sourcesBySourceId: Record<string, AutocompleteReshapeSource>;
    state: AutocompleteState;
  }) => AutocompleteReshapeSource[];
  ```
</ParamField>

<ParamField body="insights" type="boolean | InsightsPluginOptions" default={false}>
  Whether to enable the [Algolia Insights plugin](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin).

  This option accepts an object to configure the plugin.
  You can see the available options in the [plugin's documentation](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-algolia-insights/createAlgoliaInsightsPlugin/#parameters).

  If you don't pass an `insightsClient`,
  it will be automatically detected from the `window` object,
  or downloaded from the [jsDelivr CDN](https://www.jsdelivr.com).

  If you manually enable the Insights plugin, this option won't have any effect.
</ParamField>

<ParamField body="id" type="string" default="&#x22;autocomplete-0&#x22; (incremented for each instance)">
  An ID for the autocomplete to create accessible attributes.
</ParamField>

<ParamField body="onStateChange" type="(params: { state: AutocompleteState<TItem> }) => void">
  The function called when the internal state changes.
</ParamField>

<ParamField body="enterKeyHint" type="&#x22;enter&#x22; | &#x22;done&#x22; | &#x22;go&#x22; | &#x22;next&#x22; | &#x22;previous&#x22; | &#x22;search&#x22; | &#x22;send&#x22;" post={["since: v1.10.0"]}>
  The action label or icon to present for the enter key on virtual keyboards.
</ParamField>

<ParamField body="ignoreCompositionEvents" type="boolean" default={false} post={["since: v1.15.1"]}>
  Whether to update the search input value in the middle of a composition session.
  This is useful when users need to search using non-latin characters.
</ParamField>

<ParamField body="placeholder" type="string">
  The placeholder text to show in the search input when there's no query.
</ParamField>

<ParamField body="autoFocus" type="boolean" default={false}>
  Whether to focus the search input or not when the page is loaded.
</ParamField>

<ParamField body="defaultActiveItemId" type="number | null" post={["default: null"]}>
  The default item index to pre-select.

  You should use `0` when the autocomplete is used to open links,
  instead of triggering a search in an application.
</ParamField>

<ParamField body="openOnFocus" type="boolean" default={false}>
  Whether to open the panel on focus when there's no query.
</ParamField>

<ParamField body="stallThreshold" type="number" default={300}>
  How many milliseconds must elapse before considering the autocomplete experience [stalled](/doc/ui-libraries/autocomplete/core-concepts/state/#param-status).
</ParamField>

<ParamField body="initialState" type="Partial<AutocompleteState>">
  The initial state to apply when autocomplete is created.
</ParamField>

<ParamField body="environment" type="typeof window" post={["default: window"]}>
  The environment in which your application is running.

  This is useful if you're using autocomplete in a different context than `window`.
</ParamField>

<ParamField body="navigator" type="Navigator">
  An implementation of Autocomplete's Navigator API to redirect users when opening a link.

  Learn more on the [Navigator API](/doc/ui-libraries/autocomplete/core-concepts/keyboard-navigation) documentation.
</ParamField>

<ParamField body="shouldPanelOpen" type="(params: { state: AutocompleteState }) => boolean">
  The function called to determine whether the panel should open or not.

  By default, the panel opens when there are items in the state.
</ParamField>

<ParamField body="onSubmit" type="(params: { state: AutocompleteState, event: Event, ...setters }) => void">
  The function called when submitting the Autocomplete form.
</ParamField>

<ParamField body="onReset" type="(params: { state: AutocompleteState, event: Event, ...setters }) => void">
  The function called when resetting the Autocomplete form.
</ParamField>

<ParamField body="debug" type="boolean" default={false}>
  A flag to activate the debug mode.

  This is useful while developing because it keeps the panel open even when the blur event occurs.
  **Make sure to turn it off in production.**

  See [Debugging](/doc/ui-libraries/autocomplete/guides/debugging) for more information.
</ParamField>

<ParamField body="plugins">
  The plugins that encapsulate and distribute custom Autocomplete behaviors.

  See [Plugins](/doc/ui-libraries/autocomplete/core-concepts/plugins) for more information.
</ParamField>

## Components

Autocomplete exposes [`components`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-components)
to all templates to share them everywhere in the instance.

### Highlight

<ParamField body="hit" type="THit" required>
  The Algolia hit whose attribute to retrieve the highlighted parts from.
</ParamField>

<ParamField body="attribute" type="keyof THit | string[]" required>
  The attribute to retrieve the highlighted parts from.
</ParamField>

<ParamField body="tagName" type="string" default="mark">
  The tag name to use for highlighted parts.
</ParamField>

### Snippet

<ParamField body="hit" type="THit" required>
  The Algolia hit whose attribute to retrieve the snippeted parts from.
</ParamField>

<ParamField body="attribute" type="keyof THit | string[]" required>
  The attribute to retrieve the snippeted parts from.
</ParamField>

<ParamField body="tagName" type="string" default="mark">
  The tag name to use for snippeted parts.
</ParamField>

### `ReverseHighlight`

<ParamField body="hit" type="THit" required>
  The Algolia hit whose attribute to retrieve the reverse highlighted parts from.
</ParamField>

<ParamField body="attribute" type="keyof THit | string[]" required>
  The attribute to retrieve the reverse highlighted parts from.
</ParamField>

<ParamField body="tagName" type="string" default="mark">
  The tag name to use for reverse highlighted parts.
</ParamField>

### `ReverseSnippet`

<ParamField body="hit" type="THit" required>
  The Algolia hit whose attribute to retrieve the reverse snippeted parts from.
</ParamField>

<ParamField body="attribute" type="keyof THit | string[]" required>
  The attribute to retrieve the reverse snippeted parts from.
</ParamField>

<ParamField body="tagName" type="string" default="mark">
  The tag name to use for reverse snippeted parts.
</ParamField>

## Returns

The `autocomplete` function returns [state setters](/doc/ui-libraries/autocomplete/core-concepts/state#setters)
and a `refresh` method that updates the UI state with fresh sources.

These setters are useful to control the autocomplete experience from external events.

```js JavaScript icon=code theme={"system"}
const {
  setActiveItemId,
  setQuery,
  setCollections,
  setIsOpen,
  setStatus,
  setContext,
  refresh,
  update,
  destroy,
} = autocomplete(options);
```

The `autocomplete` function returns state setters and helpers:

<ParamField body="refresh" type="() => Promise<void>">
  Updates the UI state with fresh sources.
  You must call this function whenever you mutate the state with setters and want to reflect the changes in the UI.
</ParamField>

<ParamField body="update" type="(updatedOptions: Partial<AutocompleteOptions>) => void">
  Updates the Autocomplete instance with new options.
</ParamField>

<ParamField body="destroy" type="() => void">
  Destroys the Autocomplete instance and removes it from the DOM.
</ParamField>
