0

I want to track events with react-ga in my web app project. I used react-router-dom for my routing and I always used Link to redirect users. An example from my header - directing the user towards the "explore" page:

<Link to="/explore">
                <Icon
                  icon={pathname === "/explore" ? "compass" : "compass-outline"}
                />
              </Link>

How exactly to track the event "user went to '/explore'" The only guides I can find show me how to track events caused by buttons and onClick(). I have already connected my app to google analytics and it detects my current location just fine.

 useEffect(() => {
    ReactGa.initialize("UA-175518918-1");
    ReactGa.pageview(window.location.pathname + window.location.search);
  }, []);

1 Answers1

0

You have several options here:

  1. You can use Link component like this:
<Link to="/explore" onClick={e=>ReactGa.pageview('explore')}>Explore</Link>
  1. You can listen to route changes, depending on the version of the react-router the code of how to do it will vary:
  • If you use react-router-3 you can use listen method for history:
history.listen((location) => {
  ReactGa.pageview(location.pathname);
})
Anna Miroshnichenko
  • 893
  • 1
  • 5
  • 17