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 assumes that you have:
- existing markup containing an input element where you want to implement the autocomplete dropdown
First, begin with some boilerplate for the autocomplete implementation. Create a file called
index.js in your
src directory, and add the boilerplate below:
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
true ensures that the dropdown appears as soon as a user focuses the input.
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.