简体   繁体   中英

Google Analytics setup for React

I have managed to set up Google Analytics for my React application with the ReactGA library so it will send the pageview to analytics when the user navigates around.

The problem

The problem I'm facing is that I'm not sending any analytics to google on the initial page load, since the history.listen method only fires when the location changes.

My setup

In the root of my project, I initialize the connection:

const history = require("history").createBrowserHistory;
import { Router } from "react-router-dom"

ReactGA.initialize(envConstants.ANALYTICS_TRACKING_ID);

const MyApp = () => (
  <Router history={history}>
    <MyRoutes /> 
  </Router>
)

Since I only want to see which routes the users are on I have this in my router:

const MyRoutes = props => {
  props.history.listen(location => {
    // won't see this on initial load, but navigating to another route will give me this
    console.log("LISTENING") 
  })

  return (...)
}

So I wonder how I can come around this and send the first/ initial pageview when a user comes to my site. I believe I cannot achieve this with the history.listen method. So, I guess we have to add some other functionality that I'm not too sure of.

I appreciate all the help I can get with this. And if there's something unclear, please let me know.

Thanks for reading and have a nice day!

The issue is that history listen is not called on initial page load since it's only called when the location changes. Try something like the following

import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ReactGA from 'react-ga';

const trackPageView = location => {
  ReactGA.set({ page: location.pathname });
  ReactGA.pageview(location.pathname);
};

const initGa = history => {
  ReactGA.initialize('UA-XXXXXX-X', {
    debug: true
  });
  trackPageView(history.location);
  history.listen(trackPageView);
};

const history = createHistory();
initGa(history);

ReactDOM.render((
  <Router history={history}>
      <Layout />
    </Router>
), document.getElementById('root'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM