Changing behavior based on the query

Learn how to show different results depending on the query.

You may want to change which sources you use depending on the query. A typical pattern is to display a different source when the query is empty and switch once the user starts typing.

This tutorial explains how to show static predefined items when the query is empty, and results from an Algolia index when it isn't.

Prerequisites#

This tutorial assumes that you have:

  • existing markup containing an input element where you want to implement the autocomplete dropdown
  • front-end development proficiency with HTML, CSS, and JavaScript

Getting started#

First, begin with some boilerplate for the autocomplete implementation. Create a file called index.js in your src directory, and add the boilerplate below:

index.js
import { autocomplete } from '@algolia/autocomplete-js';
autocomplete({
container: '#autocomplete',
openOnFocus: true,
});

This boilerplate assumes you want to insert the autocomplete into a DOM element with autocomplete as an id. You should change the container to match your markup. Setting openOnFocus to true ensures that the dropdown appears as soon as a user focuses the input.

Adding conditional sources#

index.js
import algoliasearch from 'algoliasearch/lite';
import { autocomplete, getAlgoliaHits } from '@algolia/autocomplete-js';
const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
);
autocomplete({
container: '#autocomplete',
openOnFocus: true,
getSources({ query }) {
if (!query) {
return [
{
sourceId: 'links',
getItems() {
return [
{ label: 'Shipping', url: '#shipping' },
{ label: 'Contact', url: '#contact' },
];
},
getItemUrl({ item }) {
return item.url;
},
templates: {
item({ item }) {
return item.label;
},
},
},
];
}
return [
{
sourceId: 'products',
getItems() {
return getAlgoliaHits({
searchClient,
queries: [
{
indexName: 'instant_search',
query,
},
],
});
},
getItemUrl({ item }) {
return item.url;
},
templates: {
item({ item }) {
return item.name;
},
},
},
];
},
});

The getSources function provides access to the current query, which you can use to return sources conditionally. You can use this pattern to display predefined items like these, recent searches, and suggested searches when the query is empty. When the user begins to type, you can show search results.

When there isn't a query, this autocomplete instance returns links to Twitter and GitHub. When there is, it searches an Algolia index. For more information on using Algolia as a source, follow the Getting Started guide.

Try it out:

Note that you have access to the full autocomplete state, not only the query. It lets you compute sources based on various parameters, such as the query, but also the autocomplete status, whether the autocomplete is open or not, the context, etc.