Browse results based on a hierarchy of Facets (HierarchicalMenu) in Instantsearch JS

Raphael Terrier
InstructorRaphael Terrier
Share this video with your friends

Social Share Links

Send Tweet

The hierarchical menu widget is used to create a navigation based on a hierarchy of facet attributes. We generally implement it for categories with subcategories.

Instructor: [00:00] Hierarchical menu will help the user navigate through categories and subcategories easily. To make it work, it needs a properly formatted attribute. Let's type in a random query and look at the JSON response.

[00:13] Opening the first hit object, we can see that we have a categories key containing an array of strings. That won't be enough for the hierarchical menu prior to indexing. We will use this array to build another attribute, the hierarchical categories. This is not an array, but an object. The keys are the depth level of categories and subcategories.

[00:36] Note how in the sublevels, the root and parent levels are still present, separated by a special character, here the angle bracket. Now that we know the structure, let's add a widget. As always, the container in the HTML file first.

[00:53] In the left column, we add a div with an ID of categories. In our app.js file, we set up our widget, search.addWidget, instantsearch.widgets, hierarchicalMenu. The container is the categories ID. Nothing new so far.

[01:14] Now, for regular menus or refinement list, we would add an attribute name which would be a string. Here, it's a little different. The key is attributes with an S. The value must be an array of strings. Remembering the structure of the hierarchicalCategories attributes of our records, we can add the root level like so, hierarchicalCategories.lvl0.

[01:38] Refreshing the page, we now have the root-level categories displayed. When clicking, it refines, but no subcategories show up. Let's add them. Copying the lvl0, pasting it twice, and changing to lvl1 and lvl2. Now refreshing again.

[01:57] When refining on the root-level category appliances, we now have the chart level showing. If we refine further on dishwashers, the sublevel categories appear. We forgot to add the header of this widget, so templates, header, and categories. We now have a hierarchical menu properly set up.