DEV Community

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

Posted on

13 1 1 1 1

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.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay