InstantSearch.js provides renderState, which you can use to render custom widgets or refine the search outside the InstantSearch.js lifecycle.
Each InstantSearch widget owns its part of the search state. While this fits the majority of use cases, sometimes you might want to read the state or refine the search outside of the InstantSearch lifecycle. For example, you may want to let users refine on a specific category from a product page, and not just from a refinement list.InstantSearch.js lets you access the render state of each widget, which you can use to create custom widgets or refine the search outside the InstantSearch.js lifecycle.
The renderState property is available starting in InstantSearch.js v4.9.
In InstantSearch, the refinementList widget controls refinements for a given attribute.
You can access its state from the renderState property.
All examples in this guide assume you’ve included InstantSearch.js in your web page from a CDN. If, instead, you’re using it with a package manager, adjust how you import InstantSearch.js and its widgets for more information.
JavaScript
Report incorrect code
Copy
const search = instantsearch({ indexName, searchClient,});search.addWidgets([ // ... instantsearch.widgets.refinementList({ container: '#brand', attribute: 'brand', sortBy: ['isRefined'], }),]);search.renderState[indexName].refinementList.brand; // returns an object containing the render state
The exposed state matches the render options exposed to the connectRefinementList render options.
You can access the state of brand and use the refine method to programmatically set a refinement.
This lets you refine on a brand from anywhere in your app, even outside of the InstantSearch lifecycle. For example, you might want to let users search in the related brand whenever they visit a product page.
When refining on a brand, you might end up with no results at all. By default, the hits widget displays a “No results” message. You can customize it using the connectHits connector along with the refinementList render state.First, remove the default template for empty hits from the hits widget so it doesn’t display anything when there are no hits.
Even though you’re using the connectHits connector,
you can access the render state of the brandrefinementList.
This lets you check whether “Pear” is a selected value and display a button to remove it.The refine method is a toggle function. When you call it with a value that’s already refined, it removes it from the search state, and vice versa.
The provided options include the same state as you’d find under search.renderState[indexName].hierarchicalMenu['hierarchicalCategories.lvl0'].For example, when there are no facets to display, you can hide or collapse the hierarchicalMenu: