How to add Google Analytics to a React application?

To add Google Analytics to a React application, follow these steps:

  1. Sign up for a Google Analytics account if you don't already have one. Once signed up, create a new property for your website and note down the Tracking ID provided.

  2. Install the react-ga package by running the following command in your React project directory:

npm install react-ga
  1. Create a new file, for example, analytics.js, in your project and add the following code:
import ReactGA from 'react-ga'; export const initGA = () => { ReactGA.initialize('YOUR_TRACKING_ID'); }; export const logPageView = () => { ReactGA.set({ page: window.location.pathname }); ReactGA.pageview(window.location.pathname); };

Replace 'YOUR_TRACKING_ID' with your actual Google Analytics Tracking ID.

  1. Import and call the initGA and logPageView functions in your main App component or any component where you want to track page views:
import React, { useEffect } from 'react'; import { initGA, logPageView } from './analytics'; const App = () => { useEffect(() => { if (!window.GA_INITIALIZED) { initGA(); window.GA_INITIALIZED = true; } logPageView(); }, []); return ( <div> {/* Your App content */} </div> ); }; export default App;
  1. Ensure that your React application uses react-router for client-side routing. This setup will automatically track page views when users navigate through the application.

  2. Finally, deploy your React application. You should start seeing data in your Google Analytics account within a few hours.