Concepts / Building Search UI / Plug analytics
Dec. 19, 2018

Plug analytics

Using Algolia Insights with React InstantSearch

Loading and initializing the library

Insights library can be either loaded via jsDelivr CDN or directly bundled with your application. We recommend loading the library by adding the snippet below to your main HTML file.

1
2
3
4
5
6
7
8
9
<script>
  !function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e.aa=e.aa||function(){(e.aa.queue=e.aa.queue||[]).push(arguments)},i=a.createElement(t),c=a.getElementsByTagName(t)[0],i.async=1,i.src="https://cdn.jsdelivr.net/npm/search-insights@1.0.0",c.parentNode.insertBefore(i,c)}(window,document,"script",0,"aa");

  // Initialize library
  aa('init', {
    appId: 'APPLICATION_ID',
    apiKey: 'SEARCH_API_KEY'
  });
</script>

Enabling queryID response

To enable the queryID response from the search API, React InstantSearch enables setting custom query parameters with the Configure widget:

1
2
3
4
5
6
7
8
const App = () => (
  <InstantSearch
    indexName="INDEX_NAME"
    searchClient={searchClient}
  >
    <Configure clickAnalytics />
  </InstantSearch>
);

Reporting click and conversion events

When you want to trigger a click event depends on your implementation type and business logic. A good framework would be to send a click event once a user has clicked on something that indicates action inside the hit - for example, when a user clicks on a result (for click events) or when a user adds an item to a cart (for conversions).

This example covers how to obtain the objectID and position values for reporting. This feature is not available with the built-in widgets. But you can compose the connectors to create a new component that will have access to these values. You gonna use the Hits for access the hits and StateResults to access the value to compute the position:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const Hits = connectHits(
  connectStateResults(({ hits, searchResults }) => (
    // render the hits
  ))
);

const App = () => (
  <InstantSearch
    indexName="INDEX_NAME"
    searchClient={searchClient}
  >
    <Configure clickAnalytics />
    <Hits />
  </InstantSearch>
);

Then you can hook your click event:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const Hits = connectHits(
  connectStateResults(({ hits, searchResults }) => (
    <div>
      {hits.map((hit, index) => (
        <div key={hit.objectID}>
          <button
            onClick={() => {
              window.aa('clickedObjectIDsAfterSearch', {
                index: "INDEX_NAME",
                eventName: "Add to Cart",
                queryID: searchResults.queryID,
                objectIDs: [hit.objectID],
                positions: [searchResults.hitsPerPage * searchResults.page + index + 1],
              });
            }}
          >
            Click event
          </button>
        </div>
      ))}
    </div>
  ))
);

Or your conversion event:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const Hits = connectHits(
  connectStateResults(({ hits, searchResults }) => (
    <div>
      {hits.map((hit, index) => (
        <div key={hit.objectID}>
          <button
            onClick={() => {
              window.aa('convertedObjectIDsAfterSearch', {
                index: "INDEX_NAME",
                eventName: "Add to Favorite",
                queryID: searchResults.queryID,
                objectIDs: [hit.objectID],
              });
            }}
          >
            Conversion event
          </button>
        </div>
      ))}
    </div>
  ))
);

That’s it. You’ve just leaned how to use React InstantSearch with Insights.

Google Analytics with React InstantSearch

Even though Algolia provides an analytics tailored to your search, you might want to integrate your search into your existing analytics tools. React InstantSearch doesn’t provide a built-in widget to implement analytics with other providers.

But you can follow the same strategy that we use for the routing.

Integrating with Google Analytics requires 2 steps:

  • set up the Google Analytics library in your page
  • setup the search state change listener

To set up Google Analytics, the best way is to actually follow the reference guide.

Once the GA library is installed on your website, you can add the following:

1
2
3
4
5
6
7
8
9
10
<InstantSearch
  indexName="instant_search"
  searchClient={searchClient}
  onSearchStateChange={searchState => {
    const page = `?query=${searchState.query}`;
    window.ga('send', 'pageView', page);
  }}
>
  <SearchBox />
</InstantSearch>

Here we only send the query to Google Analytics but you are free to implement your own function. You can take a look at the StateResults reference to have an idea of the structure.

Did you find this page helpful?