Reputation: 85875
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>
Upvotes: 0
Views: 1895
Reputation: 742
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.
Upvotes: 2