Learn how to include recent searches using the Recent Searches plugin.
Most autocomplete menus include suggested searches. You can make the experience more user-friendly by adding recent searches a user has made. This UX lets users easily recall their past searches in case they want to search for them again.
This tutorial assumes that you have:
- existing markup containing an input element where you want to implement the autocomplete dropdown
Using this plugin doesn't require an Algolia application. If you plan on including other sections in your autocomplete such as suggested searches, you do need an Algolia application with the Query Suggestions feature enabled.
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.
plugins is an empty array, but you'll learn how to add the Recent Searches plugin next.
key can be any string and is required to differentiate search histories if you have multiple autocompletes on one page. The
limit defines the maximum number of recent searches to display.
recentSearchesPlugin reads from
localStorage, you won't see any recent searches in your implementation until you've made some searches. To submit a search, be sure to press Enter on the query. Once you do, you'll see it appear as a recent search. Try it out here:
createLocalStorageRecentSearchesPlugin creates a functional plugin out of the box. You may want to customize some aspects of it, depending on your use case. To change
templates or other source configuration options, you can use
transformSource. The function includes the original
source, which you should return along with any options you want to add or overwrite.
If you use Autocomplete on the same page as your main search and want to avoid reloading the full page when an item is selected, you can modify your search query state when a user selects an item with
In some cases, you may not want to use local storage for your recent search data. You may want to use session storage or handle recent searches on your back end. If so, you can use the
createRecentSearchesPlugin to implement your own storage:
This tutorial focuses on creating and adding recent searches to an autocomplete menu. Most autocomplete menus include recent searches in addition to suggested searches and possibly other items. Check out the guides on adding suggested searches and static predefined items for more information. To learn how to display multiple sections in one autocomplete, read the guide on adding multiple categories in one autocomplete.