Skip to content

[Notes] React x Google Tag Manager: adding custom events

In previous note, we set up GA and GTM; and we already could track page views in react with react-gtm-module. This time we will cover how to fire custom events with custom fields to GA through GTM custom event into GA4.

Credits: https://github.com/alinemorelli/react-gtm/issues/28 But this note adds more details, e.g. variables, GA4

Step 1: Add new user-defined variable, variable type: Page variables -> Data Layer Variable, the variable name needs to later match with the one in react app.

Step 2: In Triggers Tab, add a new trigger, type: Custom Event. The event name needs to match the one defined in react code in the future, too.

Step 3: In Tag Tab, add a new tag with type: Google Analytics: GA4 Event, and we can hook the configuration tag to be the previous one we’ve setup up. (So it automatically plugs in the measurement ID). Same place here in tag configuration, add an event parameter with the same name as previously declared in variables, and its value could be selected from variables list. After this, include the custom event just created as triggering.

Step 4: Now time for code changes. First change previous tagManagerArgs for initialization to:

const tagManagerArgs = {
  gtmId: "GTM-XXX",
  events: {
    eventName: "eventName"
  }
}

Step 5: At where we want to fire the event, inject the code below (this needs a window to be existing, so probably need to be called in useEffect())

import TagManager from "react-gtm-module";

TagManager.dataLayer({
  dataLayer: {
      event: "matchedCodeRedirect",
      code: myCode,
  },
});

Step 6: Preview, debug and publish the change.

Leave a Reply

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