React

How to set up event tracking in React?

In this article, we will learn about tracking events of our react application. We will be using Google analytics for tracking the...

Written by Shivangi Rajde · 6 min read >
How to set up events tracking in react?

In this article, we will learn about tracking events of our react application. We will be using Google analytics for tracking the usage of our application and tracking the events in our application.

For tracking events using google analytics we first need to set up somethings in our google analytics account. We will first have a look at the steps for creating our google account and integrating react application with our google analytics account.

Why do we need to have track users?

First and foremost, thing is that google analytics provides a very good representation of the reports and data collected from our application rather it be Web application or mobile application. Keeping track of the users plays a very important role in many aspects. Keeping track helps us to analyze the behavior of the users. It also helps us to modify our app as the users visiting our site prefer. Analyzing the way users perform the events and the time they stay on our application pages helps us to improve our application from the end-users point.

Please note that we will be building a sample application that will introduce us to set up a google analytics account but in a real-world situation this won’t be enough. We would require much more knowledge f the use cases for analyzing the user behavior this would just be the starting point of our journey.

Setup Google Analytics account

The first thing we need to do is visit the site: http://analytics.google.com/. You will be redirected to the Google sign-in page. If we already have a Google account then we can sign in using that account, we don’t need to create a separate account for google analytics. But if we don’t have a Google account then we need to create one by clicking on “Create account”.

sign in to GA

Once we sign in, we will be redirected to the home page of google analytics, as shown in the image below:

GA dashboard

Let’s create a new account.

Left navigation menu

Click on “admin”, in the left side drawer of our google analytics account.

Navigating to admin, we will be redirected to where we can create our new account. Click on the create account button.

Now we are in the first step to set up our new account. We need to provide an account name.

Scroll down and click on the next property after providing the name of the account we want to create.

We have successfully created a google analytics account. Now our next step would be creating a property.

Provide the relevant details for setting up a property.

In this step don’t forget to enable the Universal Analytics property. If you are not able to see such an option then you might be having a link saying “Show advanced options”. Click on the link so that we can turn on the switch for UA property. When we want to create a UA property, we need to provide our website’s URL so that we can analyze our website.

A new generation of analytics is also a choice, we can opt for using both UA property as well as google analytics 4 property, this would create multiple properties one with UA property and another one with google analytics 4 property. There is also an option provided for only creating the UA property.

Click on next after selecting relevant options.

The third step is to provide our business information. Select the relevant option(s) from the list.

Accept the Analytics Terms of Service and the Data Processing Amendment if prompted, and click Create.

We have successfully created our google analytics account and property for that account. Now we will be redirected to the admin page which would look like something as shown in the image below.

On successful creation of the account, we will be able to see the name of the account that we have created besides the search bar.

Get Tracking ID

To get the tracking ID of the account that we have created, go to the admin panel and click on the “tracking info” to get the Tracking ID.

The format of the Universal Analytics ID would be something similar to “UA-*********-*”

Setting up the Tracking ID in react project

Create a new react application using CRA. Command to create a new application using CRA

npx create-react-app events-tracking-ga

Here, events-tracking-ga is the name of the that we want to create, we can provide the name by which we want to create the project.

Once you have created your basic react application, now we have to set up our google analytics account so that we can analyze the data in our google analytics account. We will create a simple demo that will include the demonstration for adding the event tracking on submission of the form and we will also include the code that will help us analyze the number of times our logo was clicked.

We will use a package “react-ga” which is a JavaScript module that can be used to include Google Analytics tracking code in a website or app that uses React for its front-end codebase. To install the package, we need to run the command as given below so that we can include our google analytics code in our application.

npm i react-ga 

Once the package installed successfully, we would be able to write the event tracking code in our application.

Our first step will be to import the “ReactGa” dependency in our component, in this case, it is the App component.

Please note: as we will just create a demo for event tracking, we won’t be creating a separate component for the form that we will create, we will include the form in our default component that is the “App” component.

Initialize GA

GA must be initialized using initialize function before any of the other tracking functions will record any data. The values are checked and sent through to the ga(‘create’, … call.

Now, we need to initialize Google analytics in our application, “ReactGa” provides a function “initialize” to initiate the application to track our website or application. Generally, we include it in our useEffect hook in our App component so that we would initialize it as our application loads. The initialize function takes one parameter that would be the tracking ID that we can get from our google analytics account created for our application.

ReactGa.initialize("UA-19*******-*");

Here, “UA-19*– *” should be replaced with the tracking copied from the account that you created for the application, as we saw in the steps above.

Track page views

To track the number of times our page was viewed we need to call a function “pageview” with the path as the parameter.

ReactGA.pageview(path)

We can add the code as given below so that we can track the page that is viewed. We would generally add this code in our useEffect hook so that this function gets called at the time when the component loads. In the case of class component, we can add this function in “componentDidMount” function.

ReactGa.pageview(window.location.pathname + window.location.search);

Track form submission

Tracking in-page event interactions is key to understanding the use of any interactive web property. This is how we record user interactions that don’t trigger a change in URL. We would track form submission events in our application that we have added in our app component.

To track events using google analytics we would call a function “event” with multiple parameters to get proper details of the event that we want to track. Two arguments category and action that take values as a string and are required arguments when tracking the event.

import logo from "./logo.svg"; 
import { useEffect, useState } from "react"; 
import "./App.css"; 
import ReactGa from "react-ga"; 

function App() { 
  const [state, setState] = useState(); 

  useEffect(() => { 
    ReactGa.initialize("UA-19*******-*"); 
    ReactGa.pageview(window.location.pathname + window.location.search); 
  }, []); 


  const onformSubmit = () => { 
    ReactGa.event({ 
      category: "Event tracking", 
      action: "Form submitted",
      label: "Form submission", 
    }); 
    console.log("Form submitted", state); 
  }; 

  const onTextChange = (e) => { 
    const { name, value } = e.target; 
    setState({ ...state, [name]: value });
  }; 

  return ( 
    <div className="App"> 
      <ReactGa.OutboundLink eventLabel="logo" to="/" target="_self"> 
        <div> 
          <img src={logo} className="App-logo" alt="logo" /> 
        </div> 
      </ReactGa.OutboundLink> 
      <div> 
        <form> 
          <div className="form_field"> 
            <label>Name: </label> 
            <input 
              type="text" 
              onChange={onTextChange} 
              name="name" 
              value={state && state.name} 
            /> 
          </div> 
          <div className="form_field"> 
            <label>Email: </label> 
            <input 
              type="text" 
              onChange={onTextChange} 
              name="email" 
              value={state && state.email} 
            /> 
          </div> 
          <div className="form_field"> 
            <label>Phone Number: </label> 
            <input 
              type="text" 
              onChange={onTextChange} 
              name="phnNumber" 
              value={state && state.phoneNuber} 
            /> 
          </div> 
          <button onClick={onformSubmit}>Submit</button> 
        </form> 
      </div> 
    </div> 
  ); 
} 
export default App; 

App.js

Tracking Outbound links

Outbound links can directly be used as a component in your React code and the event label will be sent directly to ReactGA. Here will be using the outboundlink for tracking number of time our logo was clicked. To track the outboundlinks we need to wrap that element in the OutBoundLink provided by “ReactGa”.

<ReactGa.OutboundLink eventLabel="logo" to="/" target="_self"> 
       <div> 
         <img src={logo} className="App-logo" alt="logo" /> 
       </div> 
 </ReactGa.OutboundLink>

To check the number of events performed and perform other analyses of our application let’s go to our Google Analytics account.

To view the report, navigate to Events under the RealTime option of the Reports section on the left-hand side navigation menu. Here we will be able to view the real-time report including active users, events performed with the number of events, events performed per second/minute, and many more reports.

Summary

In this article, we learnt about setting up a google analytics account from scratch. We used the tracking Id from the account that we created and used that tracking ID in our react application. We also learnt to initialize GA in our application, track page views, track events and track external links visited.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *