1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Search an Algolia Index with Instantsearch JS searchbox and hits widgets

    Raphael TerrierRaphael Terrier
    algoliaAlgolia

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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."

    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.

    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.