React + Router + Google Tag Manager

SleepyProgrammer picture SleepyProgrammer · Apr 7, 2015 · Viewed 24.7k times · Source

I've been spending a bit of time developing an MVP at quickcypher.com. I wanted to start putting in some analytics, and it worked great for just tracking total visits, but things went south when I tried to track different URLs on my site that uses React Router.

My approach was this: Setup a GA tag that fires on some pages, using a trigger for a custom "pageview" event. When things did fire, I would set the field page to "/rap" for example. I was firing the event in the "componentDidMount" method of the top level component for each of my views. Using the debugger, I saw the event fire as expected, but for the life of me I can't get GA to acknowledge the event. GA works as expected when I simplify the tag to fire on "all pages", so I'm assuming it has something to do with React.

Has anyone successfully implemented this or run into similar problems? Is my approach all wrong? Hoping for some guidance...cheers!

Answer

chrisguitarguy picture chrisguitarguy · May 31, 2016

A bit late to the party here, but react router should need no special code to integrate with GTM. Just drop the GTM script on your page (immediately after the opening <body> tag as recommended) and let your app run as normal.

In GTM create a custom trigger for history change.

GTM Trigger Example

You can fire it on all history changes.

all history changes

Or only on some of them. Only on your production hostname, for example.

only on production

Then add a tag for your google analytics (or whatever) and configure it to fire on your history change event by clicking "More" under "Fire On" and selecting the trigger created above.

GA Example

It's also important to change the Advanced Settings of our tag to fire once per event instead of once per page. Without this, the tag will only fire on the initial page load.

once per event