Integrate Google Analytics In React Website

Google analytics with react

Google Analytics4 is one of the widely used Analytics services that help us to track, monitor, measure traffic, and analyze user actions from both websites and apps. 

Analytics is the process of discovering, collecting, tracking, and aggregating meaningful information from data. There is a variety of analytics technologies available based on data. 

Yes, in this post, we will explore one of the widely used and latest analytics technology called Google Analytics4. The current google analytics version is 4. So named GA4. 

The GA4 is a completely free version and is updated from Universal Analytics. If we want more access and more tools? Then we could go for Google analytics 360. It is paid version and includes a variety of new tools and technologies. 

There are two types of analytics methods Universal Analytics and GA4. Universal Analytics will sunset on July 1, 2023.

Prerequisites

  • Google Analytics Account and measurement ID,
  • Having knowledge of GA4 and React development is best. 

A number of steps are followed

  1. Sign up for Google Analytics and Create a measurement ID
    1. Create an Account
    2. Create a Property
    3. Create and Configure Data Streams. 
  2. Create react website and install the required plugins.
  3. Import react google analytics plugin and configure GA4 measurement ID.
  4. Run the App and check the analytics are working as expected. 

1. Sign up for Google Analytics and Create a measurement ID.

Go to the link here and sign up with your Gmail account.

Note: Currently, GA4 is not supported for non-google Gmail accounts. 

A. Create an Account for your business.

Click on the settings icon on the bottom left of the window >> Admin >> Click on Create Account to configure your data sharing. Check the screenshot. Given below

create account google analytics

An account can have more than one tracking ID based on the property and streams. 

Google analytics configure account

B. Create a property.

Property is a point-of-scale device such as a website, mobile app, blog, etc. 

It uses event-based data and cookieless measurement. Each GA4 account can have up to 100 properties.

Property setup

Under the property details, enter the property name >> Reporting time Zone >> Currency. We can edit the property details later in the settings. Click Next to move on business details section.

Property setup google analytics

Under About your Business, select the industry category, Business Type, and pick measurements of how you intend to use google analytics. For testing purposes configured with minimal setup. Check the screenshot. Given below

Business information google analytics

Change the country/ Region to accept the Google Analytics Terms of Service Agreement. 

Terms and condition google analytics

C. Create and Configure Data Streams.

The data stream is the source of information from customer interaction which will send to google analytics property. We can collect data based on platforms such as websites, Android apps, and iOS apps. Each property can have up to 50 streams.

Click on the Data stream >> Select the platform we will test on react website so I have selected web platform.

Data stream google analytics

Set up your data stream by adding the website URL, Stream Name, and enabling measurement setting. In the website URL, I have entered the ngrok URL for running HTTPS. We can test it HTTP localhost also. Give the stream name and make sure you enabled Enhancement Measurement to measure Page view, Scrolls, and Outbound Click by default. 

Once completed above configuration, Click on "Create stream" to get the web stream details. 

Web stream google analytics

Now, we got the stream details including stream Id and Measurement Id. Copy the measurement Id. We will use it for react site configuration. 

measurement id google analytics

There are two ways we can add Google tags to our websites. Given below,

  1. Manual configuration with help of developers.
     
    1. Add by third-party package.
      We can use one of the popular NPM packages named “react-ga4” which we will use in this article. Read more here
       
    2. Add tag manually.
      Copy the Google Tag available at Web stream details >>  under the Google Tag we have “configure Tag settings” click on it. Paste it inside the head tag of your project available in React project >> public >> index.html
       
  2. Configure by Google Tag Manager without any help from developers. 
    Set up Google Tag Manager by choosing the google analytics method along with its measurement Id. Read more here

2. Create react website and install required plugins

Let's dive into creating react website and integrating Google Analytics. 

Let's Create react app by running the below command. 

Create-react-app ga-test –template typescript

Install required NPM packages given below 

npm i react-router-dom

React router dom: We will use this for screen navigation.

npm i react-ga4

React GA4: One of the popular packages for integrating google tags into our website.

Open the project in your favorite code editor and check the src/index.tsx By default, we have the function named "reportWebVitals()" we will use to send user interactions to Google analytics. 

3. Import react google analytics plugin and configure GA4 measurement ID

Import BrowserRouter from ‘react-router-dom’ and add the tag inside the root render method for enabling screen navigation. 

Import ReactGA from 'react-ga4' plugin. 

Next, we should initialize GA4 along with the measurement Id we have copied from the google analytics stream. 

Make a method in the name of SendAnalytics() and add a send function inside itself including hitType and page. Here the "hitType" value is "pageview" and the page value is the current location of the screen. Make it callable by reportWebVitals on page load.

Please check below example code for references. 

 Index.tsx

import React, {useEffect} from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
import ReactGA from "react-ga4";

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
//Initialize GA4
ReactGA.initialize("G-RXSQ0HH7M8");
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>

  </React.StrictMode>
);
const SendAnalytics = ()=> {      
  ReactGA.send({
    hitType: "pageview",
    page: window.location.pathname,
  });
}
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(SendAnalytics);

I have created two files for the Home and sign-up screens.

Import the Routes tag from react-router-dom and add it inside the jsx return method. 

Import sign-up and home from the respective file path and add inside Routes tag help of Route syntax. 

App.tsx

import React from 'react';
import './App.css';
import {Routes, Route, useNavigate} from 'react-router-dom';
import Signup from './signup';
import Home from './Home';

function App() {
  return (
    <div className="App">
      <Routes>
          <Route path="/signup" element={<Signup />} />
          <Route path="/" element={<Home />} />
        </Routes>
    </div>
  );
}
export default App;

In the home tsx file, add the below code includes basic functionality for screen navigation. The "navigateToSignUp" function will trigger when the user on clicks to move the signUp screen. 

Home.tsx

import Recat from 'react';
import {useNavigate} from 'react-router-dom';

const Home = ()=> {
  const navigate = useNavigate();
  const navigateToSignUp = () => {
  navigate('/signup');
  };
    return(
        <div>
            <label> Home screen</label>
            <div>
                <button onClick={()=> navigateToSignUp()}>Move to sign Up sreen</button>
            </div>
        </div>
    )
}
export default Home;

In the sign-up screen, I have implemented a simple sign-up form for testing purposes. Use the below code for your test as well. 

Signup.tsx

import React from 'react';
import {useNavigate} from 'react-router-dom';

const Signup = ()=> {
    const navigate = useNavigate();
    const moveHome = () => {
        navigate('/');
    };
    return(
    <div className="App">
      <header className="App-header">
        <form className='form'>
        <div className="flex-container">
          <div className='input'>
            <input className='name' placeholder='UserName' />
          </div>
          <div className='input'>
            <input className='password' placeholder='Password' />
          </div>
          <div className='login-btn'>
            <button className='btn'>Sign Up</button>
          </div>
        <div style={{paddingTop:'30px'}}>
            <button onClick={()=> moveHome()}  style={{color:'black'}}>Move back</button>
        </div>
        </div>
        </form>       
      </header>
    </div>
    )
}
export default Signup;

4. Run the App and check the analytics are working as expected

Run the react app by “npm start” 

Go to the Google Analytics account dashboard >> Reports >> Realtime 

In the users in the last 30 minutes card, we will see the count is one. As the same check, the “View by page title” and “Event count by event name” cards are updated simultaneously. 

Note
Data collection will not be Active immediately and will take some time or up to 48 hours.

Check the below video for complete code and testing Google Analytics measurement. 

Conclusion 

In this post, we have learned step by step how to create a google analytics Account, Property, and stream, how we can configure GA4 in react website, and how to measure user count and page location in the GA4 in real-time. If you have any doubts, feel free to leave comments. I am always available to help you. 

If you found this post useful, please give it a like.


Similar Articles