API Reference / InstantSearch.js Widgets / hits
Widget signature
instantsearch.widgets.hits({
  container: string|HTMLElement,
  // Optional parameters
  escapeHTML: boolean,
  templates: object,
  cssClasses: object,
  transformItems: function,
});

About this widget

The hits widget is used to display a list of results.

To configure the number of hits to show, use the hitsPerPage widget or the configure widget.

Examples

1
2
3
4
5
6
7
8
9
10
11
instantsearch.widgets.hits({
  container: '#hits',
  templates: {
    item: `
      <h2>
        {{#helpers.highlight}}{ "attribute": "name" }{{/helpers.highlight}}
      </h2>
      <p>{{ description }}</p>
    `,
  },
});

Options

container
type: string|HTMLElement
Required

The CSS Selector or HTMLElement to insert the widget into.

1
2
3
instantsearch.widgets.hits({
  container: '#hits',
});
escapeHTML
type: boolean
default: true
Optional

Escapes HTML entities from hits string values.

1
2
3
4
instantsearch.widgets.hits({
  // ...
  escapeHTML: false,
});
templates
type: object
Optional

The templates to use for the widget.

1
2
3
4
5
6
instantsearch.widgets.hits({
  // ...
  templates: {
    // ...
  },
});
cssClasses
type: object
default: {}
Optional

The CSS classes to override.

  • root: the root element of the widget.
  • emptyRoot: the container element without results.
  • list: the list of results.
  • item: the list items.
1
2
3
4
5
6
7
instantsearch.widgets.hits({
  // ...
  cssClasses: {
    root: 'MyCustomHits',
    list: ['MyCustomHitsList', 'MyCustomHitsList--subclass'],
  },
});
transformItems
type: function
default: items => items
Optional

Receives the items, and is called before displaying them. Should return a new array with the same shape as the original array. Useful for mapping over the items to transform, and remove or reorder them.

If you’re transforming an attribute using the highlight widget, you need to transform item._highlightResult[attribute].value.

1
2
3
4
5
6
7
8
9
instantsearch.widgets.hits({
  // ...
  transformItems(items) {
    return items.map(item => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

Templates

empty
type: string|function
Optional

The template to use when there are no results. It exposes the results object.

1
2
3
4
5
6
instantsearch.widgets.hits({
  // ...
  templates: {
    empty: 'No results for <q>{{ query }}</q>',
  },
});
item
type: string|function
Optional

The template to use for each result. This template receives an object containing a single record. The record has a new property __hitIndex for the relative position of the record in the list of displayed hits. You can leverage the highlighting feature of Algolia through the highlight function, directly from the template system.

1
2
3
4
5
6
7
8
9
10
11
12
instantsearch.widgets.hits({
  // ...
  templates: {
    item: `
      <h2>
        {{ __hitIndex }}:
        {{#helpers.highlight}}{ "attribute": "name" }{{/helpers.highlight}}
      </h2>
      <p>{{ description }}</p>
    `,
  },
});

HTML output

1
2
3
4
5
6
7
8
9
10
11
12
13
<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>

Customize the UI - connectHits

If you want to create your own UI of the hits widget, you can use connectors.

It’s a 3-step process:

// 1. Create a render function
const renderHits = (renderOptions, isFirstRender) => {
  // Rendering logic
};

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

// 3. Instantiate
search.addWidgets([
  customHits({
    // instance params
  })
]);

Create a render function

This rendering function is called before the first search (init lifecycle step) and each time results come back from Algolia (render lifecycle step).

const renderHits = (renderOptions, isFirstRender) => {
  const {
    object[] hits,
    object results,
    function sendEvent,
    object widgetParams,
  } = renderOptions;

  if (isFirstRender) {
    // Do some initial rendering and bind events
  }

  // Render the widget
}

Rendering options

hits
type: object[]

The matched hits from the Algolia API. You can leverage the highlighting feature of Algolia through the highlight function, directly from the connector’s render function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const renderHits = (renderOptions, isFirstRender) => {
  const { hits } = renderOptions;

  document.querySelector('#hits').innerHTML = `
    <ul>
      ${hits
        .map(
          item =>
            `<li>
              ${instantsearch.highlight({ attribute: 'name', hit: item })}
            </li>`
        )
        .join('')}
    </ul>
  `;
};
results
type: object

The complete response from the Algolia API. It contains the hits but also metadata about the page, number of hits, etc. We recommend using hits rather than this option. You can also take a look at the stats widget if you want to build a widget that displays metadata about the search.

1
2
3
4
5
6
7
8
9
10
11
12
13
const renderHits = (renderOptions, isFirstRender) => {
  const { results } = renderOptions;

  if (isFirstRender) {
    return;
  }

  document.querySelector('#hits').innerHTML = `
    <ul>
      ${results.hits.map(item => `<li>${item.name}</li>`).join('')}
    </ul>
  `;
};
sendEvent
type: (eventType, hit, eventName) => void

The function to send click or conversion events. The view event is automatically sent when this connector renders hits. You can learn more about the insights middleware.

  • eventType: 'click' | 'conversion'
  • hit: Hit | Hit[]
  • eventName: string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// For example,
sendEvent('click', hit, 'Product Added');
// or
sendEvent('conversion', hit, 'Order Completed');

/*
  A payload like the following will be sent to the `insights` middleware.
  {
    eventType: 'click',
    insightsMethod: 'clickedObjectIDsAfterSearch',
    payload: {
      eventName: 'Product Added',
      index: '<index-name>',
      objectIDs: ['<object-id>'],
      positions: [<position>],
      queryID: '<query-id>',
    },
    widgetType: 'ais.hits',
  }
*/
widgetParams
type: object

All original widget options forwarded to the render function.

1
2
3
4
5
6
7
8
9
10
11
12
13
const renderHits = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

  widgetParams.container.innerHTML = '...';
};

// ...

search.addWidgets([
  customHits({
    container: document.querySelector('#hits'),
  })
]);

Create and instantiate the custom widget

We first create custom widgets from our rendering function, then we instantiate them. When doing that, there are two types of parameters you can give:

  • Instance parameters: they are predefined parameters that you can use to configure the behavior of Algolia.
  • Your own parameters: to make the custom widget generic.

Both instance and custom parameters are available in connector.widgetParams, inside the renderFunction.

const customHits = instantsearch.connectors.connectHits(
  renderHits
);

search.addWidgets([
  customHits({
    // Optional parameters
    escapeHTML: boolean,
    transformItems: function,
  })
]);

Instance options

escapeHTML
type: boolean
default: true
Optional

Escapes HTML entities from hits string values.

1
2
3
customHits({
  escapeHTML: false,
});
transformItems
type: function
default: items => items
Optional

Receives the items, and is called before displaying them. Should return a new array with the same shape as the original array. Useful for mapping over the items to transform, and remove or reorder them.

If you’re transforming an attribute using the highlight widget, you need to transform item._highlightResult[attribute].value.

1
2
3
4
5
6
7
8
customHits({
  transformItems(items) {
    return items.map(item => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

Full example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Create the render function
const renderHits = (renderOptions, isFirstRender) => {
  const { hits, widgetParams } = renderOptions;

  widgetParams.container.innerHTML = `
    <ul>
      ${hits
        .map(
          item =>
            `<li>
              ${instantsearch.highlight({ attribute: 'name', hit: item })}
            </li>`
        )
        .join('')}
    </ul>
  `;
};

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

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

Sending Click and Conversion events

Please refer to the guide on Sending Insight Events to learn about sending events from any InstantSearch widget.

Did you find this page helpful?