DEV Community

Cover image for Add Google Analytics to React/Next in 5 minutes
Duc Le
Duc Le

Posted on

Add Google Analytics to React/Next in 5 minutes

Introduction

Websites and applications have tons of trackers, but they serve many purposes, and some are good purposes.

Let's say you want to track how many users went to your websites, how many users actually use a feature, or how many users drop when doing certain actions.

One of the most outstanding tracking tool out there is Google Analytics. So I'm writing this article to show you how to integrate Google Analytics to your React apps.

Set up

First, you need to create a google account, which you probably have.

Then you need to inject some scripts for Google Tag Manager to your apps:

      <Script
        async
        strategy="afterInteractive"
        src="https://www.googletagmanager.com/gtag/js?id=YOUR ID"
      ></Script>
      <Script strategy="afterInteractive" id="gtm">
        {`
           window.dataLayer = window.dataLayer || [];
           function gtag(){dataLayer.push(arguments);}
           gtag('js', new Date());
           gtag('config', YOUR ID,{ 'debug_mode':true });
        `}
      </Script>
Enter fullscreen mode Exit fullscreen mode

The first Script tag is to install GTM, the second tag is to config Google Tag, you need to provide your GTM id, you can enable the debug mode to inspect the actions.

Sending Events

Although by default, Google provided some events built in, like page view event or scroll to bottom event. And we can create custom events on the dashboard

But in my opinion, we should fire custom events from our code, for better behavior customization. So I created a utility for this:

type WindowWithDataLayer = Window & {
  gtag: Function;
};

declare const window: WindowWithDataLayer;

type TrackerProps = {
  eventName: string;
};

export const tracker = ({ eventName }: TrackerProps) => {
  window.gtag('event', eventName);
};
Enter fullscreen mode Exit fullscreen mode

With the tracker function, we will be able to fire any event we like with a custom event name ( you can even provide parameters, just customize my function above ). This is how it can be called:

          onClick={() => {
            tracker({ eventName: 'open_projects' });
            set(open => !open);
          }}
Enter fullscreen mode Exit fullscreen mode

I fired an event name open_projects on click.

Image description

I tried to fire the event multiple times to see if it works, as you can see, it works perfectly.

Conclusion

This is just a very basic tutorial on how you can implement Google Analytics to your app, you can modify the example above to send parameters, or go to google’s dashboard to create advanced events.

Top comments (0)