简体   繁体   中英

How to setup Reactjs with Google Analytics?

I am trying to get GA to track all my pages that are being changed by React Router v4.

I seen this code using the library: react-ga

history.listen(location => {
// ReactGA.set({ page: location.pathname })
// ReactGA.pageview(location.pathname)
})

but I don't think this will log the first page.

I seen this but I don't know how to set it up on my site

https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker

My index.js looks like this

ReactDOM.render(

    <Provider routingStore={routingStore} domainStores={DomainStores} uiStores={uiStores}>
      <Router history={history}>
        <ErrorBoundary FallbackComponent={ErrorFallbackComponent}>
        <StripeProvider apiKey={stripeKey}>
          <AppContainer />
          </StripeProvider>
        </ErrorBoundary>
      </Router>
    </Provider>
  ,
  document.getElementById('app')
);

then inside "appConainter" I have "Switch" with my routes in it

  <Switch>

          <Route
            exact
            path="n"
            component={}
          />
  </Switch>

You need to include it in your AppContainer component:

import withTracker from './withTracker' which is a file that you manually create.

Then make the file called withTracker.jsx and put these contents in there:

import React, { Component, } from "react";
import GoogleAnalytics from "react-ga";

GoogleAnalytics.initialize("UA-0000000-0");

const withTracker = (WrappedComponent, options = {}) => {
  const trackPage = page => {
    GoogleAnalytics.set({
      page,
      ...options,
    });
    GoogleAnalytics.pageview(page);
  };

  // eslint-disable-next-line
  const HOC = class extends Component {
    componentDidMount() {
      // eslint-disable-next-line
      const page = this.props.location.pathname + this.props.location.search;
      trackPage(page);
    }

    componentDidUpdate(prevProps) {
      const currentPage =
        prevProps.location.pathname + prevProps.location.search;
      const nextPage =
        this.props.location.pathname + this.props.location.search;

      if (currentPage !== nextPage) {
        trackPage(nextPage);
      }
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };

  return HOC;
};

export default withTracker;

Make sure you have react-ga installed.

Then everywhere you have a route defined in AppContainer you need to call it:

<Route component={withTracker(App, { /* additional attributes */ } )} />

The documentation you linked shows how to do it.

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