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;
}
This CSS will change the display of the 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>
.
Since CSS will apply the styles of the most specific css selectors when we later add the class list to the parent <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.
Now all thats left to do is to create the JavaScript logic to dynamically add and remove the class to the parent hits div. You can see a full working example of this implementation here in this CodeSandBox.
The index.html has comments showing where code has been added and scripts have been imported. We've extracted the CSS and JS logic to separate files called viewMode.css and viewMode.js to keep it easy to read.
This is a basic example and we encourage you to make changes as you see fit to better fit your use case.