3

I have been trying to make this work for a few days, and nothing is working. The events are simply not being captured no matter what I do.

I import ReactGA at the top

import ReactGA from "react-ga";

I initialize it after import

ReactGA.initialize("TRACKING-ID", {
  debug: true
});

I create a function to handle the tracker

const GASignInHandler = name => {
  ReactGA.event({
    category: "Dashboard Home",
    action: `User Signing In As ${name}`,
    label: "Tracking users every time they sign in.",
    nonInteraction: true
  });
};

Inside my functional component called DashHome, and inside the return I call this. Pretty much if signedIn = true, run this function, if not run the console.log. This is for testing purposes obviously but I still don't see this event being logged in GA. It fires off in debug.

{signedIn ? GASignInHandler(userEmail) : console.log("signin not true")}

[react-ga] with fieldObject: {"hitType":"event","eventCategory":"Dashboard Home","eventAction":"User Signing in as My","eventLabel":"Tracking Users Every Time They Sign In.","nonInteraction":true} log.js:2 [react-ga] with trackers: undefined

I also have all the tags that GA told me to put into my public/index.html.

0rando
  • 135
  • 3
  • 9

1 Answers1

3

Putting this into index.js fixed the problem.

(function initAnalytics() {
  initGA("Tracking ID");
})();

The initGA function is manually created and is as such (this file is called index.js)

import ReactGA from "react-ga";

export const initGA = trackingID => {
  ReactGA.initialize(trackingID);
};

export const PageView = () => {
  ReactGA.pageview(window.location.pathname + window.location.search);
};

export const Event = (category, action, label) => {
  ReactGA.event({
    category,
    action,
    label
  });
};

I have also removed all the scripts that I had in public/index.html. I only have react-ga init.

It also seems you must put

ReactGA events

into a useEffect hook if youre using functional components.

0rando
  • 135
  • 3
  • 9
  • >It also seems you must put ReactGA events into a useEffect hook if youre using functional components. This is not strictly true. It's often a good idea, so they don't fire again every time the component re-renders; but in some cases (such as, when re-rendering signifies an important action), you may wish them to do so. – Andrew Feb 12 '21 at 23:28