Can I set defaultRefinement on hierarchicalMenu in the .js version of instantsearch (not react)

752 Views Asked by At

I can see that there is an defaultRefinement option on the react widget hierarchicalMenu, but I can't find it in the .js docs. Is there an equivalent in .js?

If not, is there a workaround?

instantsearch.widgets.hierarchicalMenu({
        container: '#ais-filterCatMenu',
        defaultRefinement: 'Sofa > Sovesofa',
        attributes: [
            'categories.lvl0',
            'categories.lvl1',
        ],
...
}),
1

There are 1 best solutions below

2
On BEST ANSWER

With Instantsearch.js you can define an initialUiState when initializing the search client. https://www.algolia.com/doc/api-reference/widgets/instantsearch/js/#widget-param-initialuistate

const search = instantsearch({
  // ...
  initialUiState: {
    indexName: {
      query: 'phone',
      page: 5,
    },
  },
});

I found the source of https://instantsearchjs.netlify.app/stories/?path=/story/refinements-hierarchicalmenu--with-default-selected-item on their github repo here

For example you can do something like this

const search = instantsearch({
  indexName: 'instant_search',
  searchClient,
  initialUiState: {
    instant_search: { //instant_search is index name
      hierarchicalMenu: {
        'hierarchicalCategories.lvl0': [
          'Cell Phones > Cell Phone Accessories > Car Chargers',
        ],
      },
    },
  },
});

search.addWidgets([
  instantsearch.widgets.hierarchicalMenu({
    container: '#hierarchical-menu',
    attributes: [
      'hierarchicalCategories.lvl0',
      'hierarchicalCategories.lvl1',
      'hierarchicalCategories.lvl2',
      'hierarchicalCategories.lvl3',
    ],
  }),
]);

which will end up looking like this. Edit hierarchical menu example (forked)

enter image description here