Instrumentation of React's onClick events to integrate analytics

33 Views Asked by At

We want to track user navigation in a React app - clicks on buttons, form filling, page navigation.

What we don't want - to pollute every onClick etc handlers with custom analytics code.

Does react provides API for observing clicks / text typing in React components and route navigation?

PS We'd like to add custom attributes to the components to track analytics data, observer API should get us a back link to the component so we'll be able to extract meta-data.

We'd like to introduce analytics in declarative way instead of polluting code with custom JS logic.

1

There are 1 best solutions below

2
Kenji Ginjo On

The idea here is to set up a global event listener in your app, listening to the analyticsId of every element that you want to analyze.

import React, { useEffect } from 'react';

const App = () => {

  useEffect(() => {
    const clickHandler = (event) => {
      // Check if the clicked element or its parent has a data-analytics-id attribute
      const analyticsId = event.target.getAttribute('data-analytics-id') 
                         || event.target.parentElement?.getAttribute('data-analytics-id');

      if (analyticsId) {
        // Handle your analytics logic here
        console.log(`Analytics ID: ${analyticsId}`);
      }
    };

    // Add the event listener to the document
    document.addEventListener('click', clickHandler);

    // Clean up the event listener
    return () => {
      document.removeEventListener('click', clickHandler);
    };
  }, []);

  return (
    <div>
      <button data-analytics-id="btn1">Button 1</button>
      <button data-analytics-id="btn2">Button 2</button>
      <input data-analytics-id="input1" placeholder="Input field" />
      {/* More components */}
    </div>
  );
};

export default App;