How to modify HTML output of hits container for instantsearch.js?

Hi folks,

I’m new to Algolia.

I’m having a few difficulties with modifying the generated instantsearch.js HTML of the hits container.

My search.js code:

const searchClient = algoliasearch('X', 'Y');

const search = instantsearch({
  indexName: 'index',
  searchClient
});

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: '#searchbox',
    placeholder: 'Search for products'
  }),

  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      item: `
        <div class="div1">
          <div class="div2">
            <img" src="{{img}}" alt="{{product.name}}">
          </div>
          <div class="div3">
            <h2>
              <a class="{{#sale}}red{{/sale}}{{^sale}}black{{/sale}}" href="{{url}}">{{title}}</a>
            </h2>
          </div>
        `
      }
    })
  ]);

search.start();

Here’s the output:

<div id="hits"><div>
  <div class="ais-Hits">
    <ol class="ais-Hits-list">
      <li class="ais-Hits-item">
        ... [#hits template]
      </li>
    </ol>
  </div>
</div>

If I understand correctly, I need to create and instantiate a custom widget to modify the HTML.

Using the example from the docs:

// Create the render function
const renderHits = (renderOptions, isFirstRender) => {
  const { hits, widgetParams } = renderOptions;

  widgetParams.container.innerHTML = `
    <div class="mydiv">
      <ul class="mylist">
      ${hits
        .map(
          item =>
            `<li class="{{#stock}}black{{/stock}}{{^stock}}red{{/stock}}">
              ${instantsearch.highlight({attribute: 'name', hit: item})}
            </li>`
        )
        .join('')}
    </ul> 
   </div>
  `;
};

// Create the custom widget
const customHits = instantsearch.connectors.connectHits(renderHits);

// Instantiate the custom widget
search.addWidgets([
  customHits({
    container: document.querySelector('#hits'),
  })
]);

But I’m not sure how to modify this further as I’m new to javascript as well. This is the desired output I would like:

<div id="hits"><div>
    <div class="mydiv">
      <ul class="mylist">
      	<li class="black or red depending on the logic">
        ... [#hits template]
      </li>
    </ul>
  </div>
</div>

Any suggestions are most welcome. Thank you.

HI @heydave,

Welcome to the Algolia Community!

I’m not sure I understand your question.

Could you add your code to a codesandbox to demonstrate the problem?

We have some codesandbox starter templates to help get you started.

This wiil help us troubleshoot your code.

I look forward to your reply!

@cindy.cullen Thanks for the reply. I managed to get this to work. Just an error on my part. Tried to delete my post, but I’m not permitted to do so on here.

1 Like

Thanks for letting us know, all good then!