Skip to main content
Autocomplete is also available as an experimental widget in InstantSearch, making it easier to integrate into your search experience. To learn more, see the API reference for InstantSearch.js or React InstantSearch.
By default, it uses Preact 10 to render templates.

Installation

First, you need to install the package.
npm install @algolia/autocomplete-js
Then import it in your project:
JavaScript
import { autocomplete } from "@algolia/autocomplete-js";
If you don’t use a package manager, you can use the HTML script element:
HTML
<script
  src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-js@1.19.4/dist/umd/index.production.js"
  integrity="VaQwRODmAHrukHfV+gCLjVfzWyj0veQpSK9hu77pt6A="
  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.
JavaScript
<div id="autocomplete"></div>
This example uses Autocomplete with an Algolia index, along with the algoliasearch API client. All Algolia utility functions to retrieve hits and parse results are available directly in the package.
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",
            });
          },
        },
      },
    ];
  },
});

Parameters

container
string | HTMLElement
required
The container for the Autocomplete search box. You can either pass a CSS selector or an Element. If there are several containers matching the selector, Autocomplete picks up the first one.
panelContainer
string | HTMLElement
The container for the Autocomplete panel. You can either pass a CSS selector or an Element. If there are several containers matching the selector, Autocomplete picks up the first one.
panelPlacement
"start" | "end" | "full-width" | "input-wrapper-width"
default:"input-wrapper-width"
The panel’s horizontal position.
insights
boolean | InsightsPluginOptions
default:false
Whether to enable the Algolia Insights plugin.This option accepts an object to configure the plugin. You can see the available options in the plugin’s documentation.If you don’t pass an insightsClient, it will be automatically detected from the window object, or downloaded from the jsDelivr CDN.If you manually enable the Insights plugin, this option won’t have any effect.
translations
Translations
Type definition
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.
classNames
ClassNames
Class names to inject for each created DOM element. This is useful to style your autocomplete with external CSS frameworks.
Type definition
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;
}>;
components
Components to register in the Autocomplete rendering lifecycles. Registered components become available in templates, render, and in renderNoResults.
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,
    );
  },
});
Four components are registered by default:
  • Highlight to highlight matches in Algolia results.
  • Snippet to snippet matches in Algolia results.
  • ReverseHighlight to reverse highlight matches in Algolia results.
  • ReverseSnippet to reverse highlight and snippet matches in Algolia results.
autocomplete({
  // ...
  getSources({ query }) {
    return [
      {
        getItems() {
          return [
            // ...
          ];
        },
        templates: {
          item({ item, components }) {
            return components.Highlight({ hit: item, attribute: "name" });
          },
        },
      },
    ];
  },
});
render
function
Type definition
(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:
JavaScript
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.
autocomplete({
  // ...
  render({ sections, render, html }, root) {
    render(
      html`<div class="aa-PanelLayout aa-Panel--scrollable">${sections}</div>`,
      root,
    );
  },
});
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.
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,
    );
  },
});
renderNoResults
function
Type definition
(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:
JavaScript
autocomplete({
  // ...
  renderNoResults({ state, render }, root) {
    render(`No results for "${state.query}".`, root);
  },
});
renderer
The virtual DOM implementation to plug to Autocomplete. It defaults to Preact.
detachedMediaQuery
string
default:"(max-width: 680px)"
The detached mode turns the dropdown display into a full screen, modal experience.For more information, see Detached mode.
The autocomplete function also accepts all the props that createAutocomplete supports:
getSources
The sources to get the collections from.
reshape
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 for more information.
TypeScript
type Reshape = (params: {
  sources: AutocompleteReshapeSource[];
  sourcesBySourceId: Record<string, AutocompleteReshapeSource>;
  state: AutocompleteState;
}) => AutocompleteReshapeSource[];
insights
boolean | InsightsPluginOptions
default:false
Whether to enable the Algolia Insights plugin.This option accepts an object to configure the plugin. You can see the available options in the plugin’s documentation.If you don’t pass an insightsClient, it will be automatically detected from the window object, or downloaded from the jsDelivr CDN.If you manually enable the Insights plugin, this option won’t have any effect.
id
string
An ID for the autocomplete to create accessible attributes.
onStateChange
(params: { state: AutocompleteState<TItem> }) => void
The function called when the internal state changes.
enterKeyHint
"enter" | "done" | "go" | "next" | "previous" | "search" | "send"
since: v1.10.0
The action label or icon to present for the enter key on virtual keyboards.
ignoreCompositionEvents
boolean
default:false
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.
placeholder
string
The placeholder text to show in the search input when there’s no query.
autoFocus
boolean
default:false
Whether to focus the search input or not when the page is loaded.
defaultActiveItemId
number | null
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.
openOnFocus
boolean
default:false
Whether to open the panel on focus when there’s no query.
stallThreshold
number
default:300
How many milliseconds must elapse before considering the autocomplete experience stalled.
initialState
Partial<AutocompleteState>
The initial state to apply when autocomplete is created.
environment
typeof window
default: window
The environment in which your application is running.This is useful if you’re using autocomplete in a different context than window.
navigator
Navigator
An implementation of Autocomplete’s Navigator API to redirect users when opening a link.Learn more on the Navigator API documentation.
shouldPanelOpen
(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.
onSubmit
(params: { state: AutocompleteState, event: Event, ...setters }) => void
The function called when submitting the Autocomplete form.
onReset
(params: { state: AutocompleteState, event: Event, ...setters }) => void
The function called when resetting the Autocomplete form.
debug
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 for more information.
plugins
The plugins that encapsulate and distribute custom Autocomplete behaviors.See Plugins for more information.

Components

Autocomplete exposes components to all templates to share them everywhere in the instance.

Highlight

hit
THit
required
The Algolia hit whose attribute to retrieve the highlighted parts from.
attribute
keyof THit | string[]
required
The attribute to retrieve the highlighted parts from.
tagName
string
default:"mark"
The tag name to use for highlighted parts.

Snippet

hit
THit
required
The Algolia hit whose attribute to retrieve the snippeted parts from.
attribute
keyof THit | string[]
required
The attribute to retrieve the snippeted parts from.
tagName
string
default:"mark"
The tag name to use for snippeted parts.

ReverseHighlight

hit
THit
required
The Algolia hit whose attribute to retrieve the reverse highlighted parts from.
attribute
keyof THit | string[]
required
The attribute to retrieve the reverse highlighted parts from.
tagName
string
default:"mark"
The tag name to use for reverse highlighted parts.

ReverseSnippet

hit
THit
required
The Algolia hit whose attribute to retrieve the reverse snippeted parts from.
attribute
keyof THit | string[]
required
The attribute to retrieve the reverse snippeted parts from.
tagName
string
default:"mark"
The tag name to use for reverse snippeted parts.

Returns

The autocomplete function returns 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.
JavaScript
const {
  setActiveItemId,
  setQuery,
  setCollections,
  setIsOpen,
  setStatus,
  setContext,
  refresh,
  update,
  destroy,
} = autocomplete(options);
The autocomplete function returns state setters and helpers:
refresh
() => 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.
update
(updatedOptions: Partial<AutocompleteOptions>) => void
Updates the Autocomplete instance with new options.
destroy
() => void
Destroys the Autocomplete instance and removes it from the DOM.