Analytics Implementation Guide

Is there an equivalent to this Pages Analytics guide for Search Analytics in React?

I’m trying to fire search analytics events when someone clicks a CTA on a result card. For pages this can be done by using the eventName prop on the Link component. Is there an equivalently simple way to do this for search?

Specifically, I’m wondering if I need to implement logic to make sure that the analytics event fires before the page navigates away, or if that logic can be handled for me by the library. I’m worried that just adding a report call in the link’s onClick isn’t safe enough.

Thanks!

Hey Ben,

Right now we are unfortunately lacking in documentation on how to use the Analytics SDK for Search but we’re working adding a guide similar to the Pages one!

To answer your question, yes you do need to implement that logic, which could you do by preventing the default behavior, like this:

import React from 'react';
import { useSearchAnalytics } from "@yext/search-ui-react";

const MyComponent = () => {
  const analytics = useSearchAnalytics(); 
  const handleClick = (event) => {
    event.preventDefault();
    
    searchAnalytics.report({
      type: 'CTA_CLICK',
      entityId: '1',
      verticalKey: 'people',
      searcher: 'VERTICAL',
      queryId: '12345678-1234-1234-1234-123456789012'
    });

    // Finally, navigate to the desired URL using either `window.location` or React Router
    const targetUrl = event.target.href;
    window.location.href = targetUrl;
  };

  return (
    <div>
      <a href="https://example.com" onClick={handleClick}>Click me</a>
    </div>
  );
};

export default MyComponent;

I recognize this is a little annoying. We are working on ways to make this more ergonomic in the future.

1 Like