Integrate Google Analytics in Your React App

Home » Programming » Integrate Google Analytics in Your React App
Google Analytics

Integrate Google Analytics in Your React App

Integrating Google Analytics into your React app is a great way to track user interactions and gather insights on your app’s performance. This blog will guide you through the steps to set up Google Analytics in your React project.

 

1. Setting Up Google Analytics:

Firstly, you need to create a Google Analytics account and set up a property for your app. Navigate to the Google Analytics website, sign in, and follow the instructions to create a new property. Once set up, you’ll receive a tracking ID (e.g., UA-XXXXXX-X).

 

2. Installing React-GA:

Install the react-ga package.  Open your terminal and run the following command:

npm install react-ga

 

3. Initializing Google Analytics:

Import react-ga and configure it with your tracking ID. Typically, this is done in your app’s main entry file (e.g., index.js).

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import ReactGA from 'react-ga';

// Initialize Google Analytics
ReactGA.initialize('UA-XXXXXX-X');

ReactDOM.render(<App />, document.getElementById('root'));

 

4. Tracking Page Views:

When you need to track page views. You can use React Router’s history object to listen for route changes and send pageview hits to Google Analytics. Update your App.js as follows:

import React, { useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch, useLocation } from 'react-router-dom';
import ReactGA from 'react-ga';

function usePageViews() {
  const location = useLocation();

  useEffect(() => {
    ReactGA.pageview(location.pathname + location.search);
  }, [location]);
}

function App() {
  usePageViews();

  return (
    <Router>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </Router>
  );
}

export default App;

 

5. Tracking Custom Events:

In addition to page views, you can track custom events. For example, track a button click:

import React from 'react';
import ReactGA from 'react-ga';

function handleClick() {
  ReactGA.event({
    category: 'Button',
    action: 'Clicked the Example Button'
  });
}

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

export default ExampleComponent;

 

Conclusion:

Google Analytics allows you to gain valuable insights into user behavior and app performance. By following these steps, you can easily set up and configure Google Analytics, track page views, and log custom events.