Skip to content

Latest commit

 

History

History
137 lines (108 loc) · 3.08 KB

File metadata and controls

137 lines (108 loc) · 3.08 KB
id autocomplete-js
title autocomplete

This function creates a JavaScript autocomplete experience.

Example

<div id="autocomplete"></div>
import algoliasearch from 'algoliasearch/lite';
import {
  autocomplete,
  getAlgoliaHits,
  reverseHighlightItem,
} from '@algolia/autocomplete-js';

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

const autocompleteSearch = autocomplete({
  container: '#autocomplete',
  getSources() {
    return [
      {
        getItemInputValue: ({ item }) => item.query,
        getItems({ query }) {
          return getAlgoliaHits({
            searchClient,
            queries: [
              {
                indexName: 'instant_search_demo_query_suggestions',
                query,
                params: {
                  hitsPerPage: 4,
                },
              },
            ],
          });
        },
        templates: {
          item({ item }) {
            return reverseHighlightItem({ item, attribute: 'query' });
          },
        },
      },
    ];
  },
});

Reference

autocomplete accepts all the props that createAutocomplete supports.

container

string | HTMLElement | required

The container for the autocomplete search box. You can either pass a CSS selector or an Element. The first element matching the provided selector will be used as container.

import CreateAutocompleteProps from './partials/createAutocomplete-props.md'

dropdownPlacement

"start" | "end" | "full-width" | "input-wrapper-width" | defaults to "input-wrapper-width"`

The dropdown horizontal position.

classNames

ClassNames

The class names to inject in each created DOM element. It it useful to design with external CSS frameworks.

type ClassNames = {
  root?: string;
  form?: string;
  label?: string;
  inputWrapper?: string;
  input?: string;
  completion?: string;
  resetButton?: string;
  listContainer?: string;
  source?: string;
  sourceHeader?: string;
  list?: string;
  listItem?: string;
  sourceFooter?: string;
};

render

(params: { root: HTMLElement, sections: HTMLElement[], state: AutocompleteState<TItem> }) => void

Function called to render the autocomplete results. It is useful for rendering sections in different row or column layouts.

The default implementation appends all the sections to the root:

autocomplete({
  // ...
  render({ root, sections }) {
    for (const section of sections) {
      root.appendChild(section);
    }
  },
});

Returned props

const {
  setSelectedItemId,
  setQuery,
  setCollections,
  setIsOpen,
  setStatus,
  setContext,
  refresh,
} = autocomplete(options);

autocomplete returns all the state setters and refresh method that updates the UI state.

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