To add Google Analytics to a React application, follow these steps:
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.
Install the react-ga package by running the following command in your React project directory:
npm install react-ga
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.
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;
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.
Finally, deploy your React application. You should start seeing data in your Google Analytics account within a few hours.