React + Router + Google Tag Manager

旧巷老猫 提交于 2019-12-02 18:40:19

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.

You can fire it on all history changes.

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

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.

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.

This could be due to misconfiguration of your google analytics account, but assuming that you can fire the initial pageview event back to GA, here is a recipe that taps into react-router's willTransitionTo hook. It also uses react-google-analytics. First npm install react-google-analytics.

Then configure your app like so:

var React = require('react');
var Router = require('react-router');
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var ga = require('react-google-analytics');
var GAInitiailizer = ga.Initializer;

// some components mapped to routes
var Home = require('./Home');
var Cypher = require('./Cypher');

var App = React.createClass({
  mixins: [Router.State],
  statics: {
    willTransitionTo: function(transition, params, query, props) {
      // log the route transition to google analytics
      ga('send', 'pageview', {'page': transition.path});
    }
  },
  componentDidMount: function() {
    var GA_TRACKING_CODE = 'UA-xxxxx';
    ga('create', GA_TRACKING_CODE);
    ga('send', 'pageview');
  },
  render: function() {
    return (
      <div>
        <RouteHandler />
        <GAInitiailizer />
      </div>
    );
  }
});

var routes = (
  <Route path="/" handler={App} >
    <DefaultRoute handler={Home} />
    <Route name="cypher" path="/cypher" handler={Cypher} />
  </Route>
);

Router.run(routes, function (Handler) {
  React.render(<Handler />, document.body);
});

module.exports = App;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!