Basic Autocomplete Setup
This code sets up a basic autocomplete experience using Algolia's search client and the preset provided by @algolia/autocomplete-preset-algolia. It initializes the autocomplete with a container and the necessary search client and index name.
const { autocomplete } = require('@algolia/autocomplete-js');
const { createAlgoliaPreset } = require('@algolia/autocomplete-preset-algolia');
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
autocomplete({
container: '#autocomplete',
presets: [
createAlgoliaPreset({
searchClient,
indexName: 'your_index_name',
}),
],
});
Customizing Autocomplete Sources
This code demonstrates how to customize the sources for the autocomplete. It uses the `getSources` function to define a custom source that queries the Algolia index and returns items based on the search query.
const { autocomplete } = require('@algolia/autocomplete-js');
const { createAlgoliaPreset } = require('@algolia/autocomplete-preset-algolia');
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
autocomplete({
container: '#autocomplete',
presets: [
createAlgoliaPreset({
searchClient,
indexName: 'your_index_name',
getSources({ query }) {
return [
{
sourceId: 'products',
getItems() {
return searchClient.search([{ indexName: 'your_index_name', query }]);
},
templates: {
item({ item }) {
return `<div>${item.name}</div>`;
},
},
},
];
},
}),
],
});