How to track a custom Google Analytics event in ReactJS or GatsbyJS
A step by step tutorial on tracking custom Google Analytics events for UA and GA4 trackers in ReactJS or GatsbyJS.
Step One: Add the dependencies
In terminal, set your project folder as the current directory and add the following dependencies.
react-ga for UA trackers
yarn add react-ga
react-ga4 for GA4 trackers
yarn add react-ga4
Step Two: Create the functionality
Add the following functionality to your project.
We recommend adding it to the utils folder, under a google-analytics subfolder.
For more information about the potential that is offered by these libraries please visit the respective links below.
Step Three: Create the structure for the events and actions
This step is optional but highly recommended as it helps manage the codebase.
Create a folder within utils/google-anayltics called Events.
Within this folder create a subfolder for every event type that you are seeking to track.
Our example demonstrates a category and an action, without a label, as the label for our form is the pathname for wherever the form is found. We recommend adding labels that are used across the system to this folder within utilities to ease managing and updating events.
Step Four: Initialize Google Analytics
At the root of your application, initialize the Google Analytics tracker by importing the function you created in step 2.
We recommend using the useEffect react hook to initialize Google Analytics on page load, on all pages of your application.
Step Five: Track Events
In your application, import the tracking functionality that you created in step 2 and the events created in step 3 and track your events.
Step Six: Verify
Navigate to Google Analytics and confirm that the events are being tracked.
Please note that in the event that you have filtered yourself out of your data, you will have to navigate to the Unfiltered View (Raw Data) to see your events for your UA tracker.
We are actively looking for feedback on how to improve this resource. Please send us a note to firstname.lastname@example.org with any thoughts or feedback you may have.