React + Router + Google Tag Manager

前端 未结 2 742
北荒
北荒 2021-01-31 10:07

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 thin

2条回答
  •  醉酒成梦
    2021-01-31 10:59

    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 (
          
    ); } }); var routes = ( ); Router.run(routes, function (Handler) { React.render(, document.body); }); module.exports = App;

提交回复
热议问题