Link to the CodeSandBox From this Article
Algolia does not have an official widget with a button to switch the display of your hits between grid and list view, however you can create this with a small amount of custom CSS.
Assuming we're using the vanilla Javascript version of the InstantSearch Hits Widget with no customization or connectors this is the default html the widget will render in the hits container.
<div class="ais-Hits">
<ol class="ais-Hits-list">
<li class="ais-Hits-item">
...
</li>
<li class="ais-Hits-item">
...
</li>
<li class="ais-Hits-item">
...
</li>
</ol>
</div>
The hits container is usually an empty <div
id='hits'></div>
that you place in your html. The hits widget targets the container div by its id and renders the HTML within it.
The container <div
id='hits'></div>
is the top level HTML element. When the widget renders it adds a div with no id or class, with a child ais-Hits
div which has then has the child element ais-Hits-list
div.
The ais-Hits-List
is where we want to change our display so we can affect all of its child ais-Hits-item
elements. There's many way's you can do this but one of the easiest ways would be to add a class to the root parent container <div
id='hits'></div>
that has css that will target the
ais-Hits-list
. Consider the following CSS.
#hits .ais-Hits-list {
display: grid;
grid-template-columns: 1fr 1fr;
width: 100%;
}
#hits.list .ais-Hits-list {
grid-template-columns: 1fr;
}
ais-Hits-list
that is a descendant of the parent hits container. Taking advantage of CSS Specificity we can add a more specific declaration for when the hits container has the class "list" on <div
id='hits'></div>
. <div
id='hits'></div>
our second declaration will override the first. This gives us a default grid display and the option to add a class to the parent hits div to change the view to list.