| id | autocomplete-js |
|---|---|
| title | autocomplete |
This function creates a JavaScript autocomplete experience.
<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' });
},
},
},
];
},
});autocomplete accepts all the props that createAutocomplete supports.
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'
"start" | "end" | "full-width" | "input-wrapper-width" | defaults to"input-wrapper-width"`
The dropdown horizontal position.
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;
};
(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);
}
},
});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.