UI Libraries / Autocomplete / createAutocomplete

The createAutocomplete function returns methods to help you create an autocomplete experience from scratch. This is fully headless: you’re in charge of creating your own autocomplete renderer.

Building a custom renderer is an advanced pattern. You don’t need it unless you’ve reached limitations with autocomplete-js and its templating capabilities.

Installation

First, you need to install the package.

1
2
3
yarn add @algolia/autocomplete-core
# or
npm install @algolia/autocomplete-core

Then import it in your project:

1
import { createAutocomplete } from '@algolia/autocomplete-core';

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

1
2
3
4
<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-core"></script>
<script>
  const { createAutocomplete } = window['@algolia/autocomplete-core'];
</script>

Example

This example uses the package along with the algoliasearch API client and getAlgoliaResults function from the Autocomplete Algolia preset. It returns a set of functions to build an autocomplete experience.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import algoliasearch from 'algoliasearch/lite';
import { createAutocomplete } from '@algolia/autocomplete-core';
import { getAlgoliaResults } from '@algolia/autocomplete-preset-algolia';

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

const autocomplete = createAutocomplete({
  getSources() {
    return [
      {
        sourceId: 'querySuggestions',
        getItemInputValue: ({ item }) => item.query,
        getItems({ query }) {
          return getAlgoliaResults({
            searchClient,
            queries: [
              {
                indexName: 'instant_search_demo_query_suggestions',
                query,
                params: {
                  hitsPerPage: 4,
                },
              },
            ],
          });
        },
      },
    ];
  },
});

Parameters

getSources

The sources to get the collections from.

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 for more information.

1
2
3
4
5
type Reshape = (params: {
  sources: AutocompleteReshapeSource[];
  sourcesBySourceId: Record<string, AutocompleteReshapeSource>;
  state: AutocompleteState;
}) => AutocompleteReshapeSource[];
id
type: string
default: "autocomplete-0" (incremented for each instance)

An ID for the autocomplete to create accessible attributes.

onStateChange
type: (params: { state: AutocompleteState<TItem> }) => void

The function called when the internal state changes.

placeholder
type: string

The placeholder text to show in the search input when there’s no query.

autoFocus
type: boolean
default: false

Whether to focus the search input or not when the page is loaded.

defaultActiveItemId
type: 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
type: boolean
default: false

Whether to open the panel on focus when there’s no query.

stallThreshold
type: number
default: 300

How many milliseconds must elapse before considering the autocomplete experience stalled.

initialState
type: Partial<AutocompleteState>

The initial state to apply when autocomplete is created.

environment
type: 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
type: Navigator

An implementation of Autocomplete’s Navigator API to redirect the user when opening a link.

Learn more on the Navigator API documentation.

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.

onSubmit
type: (params: { state: AutocompleteState, event: Event, ...setters }) => void

The function called when submitting the Autocomplete form.

onReset
type: (params: { state: AutocompleteState, event: Event, ...setters }) => void

The function called when resetting the Autocomplete form.

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 for more information.

plugins

The plugins that encapsulate and distribute custom Autocomplete behaviors.

See Plugins for more information.

Returns

The createAutocomplete function returns prop getters, state setters, and a refresh method that updates the UI state.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const {
  getEnvironmentProps,
  getRootProps,
  getFormProps,
  getInputProps,
  getItemProps,
  getLabelProps,
  getListProps,
  setActiveItemId,
  setQuery,
  setCollections,
  setIsOpen,
  setStatus,
  setContext,
  refresh,
  update,
  destroy,
} = createAutocomplete(options);

The createAutocomplete function returns state setters and additional helpers:

refresh
type: () => Promise<void>

Updates the UI state. You must call this function whenever you mutate the state with setters and want to reflect the changes in the UI.

update
type: (updatedOptions: Partial<AutocompleteOptions>) => void

Updates the Autocomplete instance with new options.

destroy
type: () => void

Destroys the Autocomplete instance, cleans up the DOM mutations and event listeners.

Did you find this page helpful?