How to integrate React with Google Analytics?

by aniyah.green , in category: SEO Tools , 8 months ago

How to integrate React with Google Analytics?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by june.crooks , 8 months ago

@aniyah.green 

To integrate React with Google Analytics, you can follow these steps:

  1. Install the react-ga package using npm or yarn:
1
2
3
npm install react-ga
# or
yarn add react-ga


  1. Create a separate file, e.g., analytics.js, and import the react-ga package:
1
2
3
4
5
6
import ReactGA from 'react-ga';

// Initialize Google Analytics
ReactGA.initialize('YOUR_GA_TRACKING_ID');

export default ReactGA;


  1. Use the react-ga package in your React application. For example, in your App.js file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import ReactGA from './analytics';

function App() {
  // Track page view on component mount
  useEffect(() => {
    ReactGA.pageview(window.location.pathname);
  }, []);

  return (
    <div>
      {/* Your app content */}
    </div>
  );
}

export default App;


  1. To track events, you can call ReactGA.event() with appropriate parameters. For instance:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import ReactGA from './analytics';

function SomeComponent() {
  const handleClick = () => {
    // Track button click event
    ReactGA.event({
      category: 'Button',
      action: 'Click',
      label: 'Button Label',
    });
  };

  return (
    <button onClick={handleClick}>Click Me</button>
  );
}


Remember to replace 'YOUR_GA_TRACKING_ID' in step 2 with your actual Google Analytics Tracking ID. With these steps, you should be able to integrate React with Google Analytics and start tracking page views and events in your application.