The HitsWithInsights connector provides the logic to build a custom widget that displays search results with automatic Insights tracking.
Usage
import { connectHitsWithInsights } from 'instantsearch.js/es/connectors';
const customHitsWithInsights = connectHitsWithInsights(
(renderOptions, isFirstRender) => {
const { items, insights, widgetParams } = renderOptions;
const { container } = widgetParams;
container.innerHTML = `
<div class="hits">
${items.map(item => `
<div class="hit" data-id="${item.objectID}">
<h3>${item.name}</h3>
<p>${item.description}</p>
<button class="click-btn">Track Click</button>
</div>
`).join('')}
</div>
`;
// Track click events
container.querySelectorAll('.click-btn').forEach((btn, index) => {
btn.addEventListener('click', () => {
insights('clickedObjectIDsAfterSearch', {
eventName: 'Product Clicked',
objectIDs: [items[index].objectID],
});
});
});
}
);
search.addWidgets([
customHitsWithInsights({
container: document.querySelector('#hits'),
}),
]);
Connector Options
This connector accepts the same options as connectHits:
Whether to escape HTML tags from hits string values.
transformItems
(items: object[]) => object[]
Function to transform the items passed to the templates.transformItems(items) {
return items.map(item => ({
...item,
title: item.name.toUpperCase(),
}));
}
Render Options
This connector provides the same render options as connectHits, plus:
The matched hits from the Algolia API.
The matched hits from the Algolia API.This parameter is deprecated. Use items instead.
The complete response from the Algolia API.
The banner to display above the hits.
insights
(method: string, payload: object) => void
Helper function to send Insights events. This function automatically infers query parameters from the search results.Supported methods:
clickedObjectIDsAfterSearch: Track clicks on search results
convertedObjectIDsAfterSearch: Track conversions from search results
// Track a click event
insights('clickedObjectIDsAfterSearch', {
eventName: 'Product Clicked',
objectIDs: ['object1'],
});
// Track a conversion event
insights('convertedObjectIDsAfterSearch', {
eventName: 'Product Purchased',
objectIDs: ['object1', 'object2'],
});
sendEvent
(eventType: string, hits: object | object[], eventName?: string) => void
Sends an event to the Insights middleware.
bindEvent
(eventType: string, hits: object | object[], eventName?: string) => string
Returns a string for the data-insights-event attribute for the Insights middleware.
The options passed to the connector.