Search an Algolia Index with Instantsearch JS searchbox and hits widgets

Raphael Terrier
InstructorRaphael Terrier

Share this video with your friends

Send Tweet
Published 4 years ago
Updated a year ago

In this lesson we’ll build a search experience reduced to it’s 2 essential components : a search input and the displayed results. As simple as it is, to build this from scratch would require a fair amount of work. Between listening to the input, making the api call, parsing and displaying the result... To build this using Algolia’s Instantsearch library requires a few lines of code with simply two widgets: the Searchbox and the Hits widget.

Instructor: [00:00] To add our searchBox and hits widgets, we first need to create containers on the HTML page. While doing so, we'll take care of structuring the layout of it. We'll add a header and a main tag. The header will contain the search box. The main tag will hold the rest of our UI.

[00:18] Adding the div with an ID of searchBox in the header, then adding another div with an ID of hits in the main tag. That's it for now on the HTML page. Let's move over to our app.js file.

[00:33] We'll take care of our search box first. search.addWidget, instantsearch.widgets, and then the searchBox widget. As always, the first thing to configure is the container. Here, we've previously set a div with a searchBox ID. Let's add it in the config.

[00:52] Loading the index page, we now have a nice search box where we can type in and clear content. One thing that is missing from this widget, though, and that is a best practice in search in general, is to give a hint to our user on what they can search for.

[01:07] This can be easily done by providing a nice placeholder in the search input. To do that, we'll leverage the placeholder attribute of our widget. As a string, we'll add "Search for products, brands, or categories."

[01:21] Refreshing the browser, we now have a more helpful placeholder. Our search box is looking good. Let's take care of showing some results onto the page now with the hits widget. Same process, search.addWidget, instantsearch.widgets, and the hits widget.

[01:39] We configure the container, #hits, as we previously added this div to our index.html page. We can now see individual hits displayed as raw JSON objects. Not particularly sexy yet, but it does help you confirm that the search works as expected. When typing in the search box, results are properly refreshed.