I'm trying set up Google Analytics on my react site, and have come across a few packages, but none of which has the kind of set up that I have in terms of examples. Was hoping someone could shed some light on this.
The package I'm looking at is, react-ga.
My render method on my index.js
looks like this.
React.render((
<Router history={createBrowserHistory()}>
<Route path="/" component={App}>
<IndexRoute component={Home} onLeave={closeHeader}/>
<Route path="/about" component={About} onLeave={closeHeader}/>
<Route path="/gallery" component={Gallery} onLeave={closeHeader}/>
<Route path="/contact-us" component={Contact} onLeave={closeHeader}>
<Route path="/contact-us/:service" component={Contact} onLeave={closeHeader}/>
</Route>
<Route path="/privacy-policy" component={PrivacyPolicy} onLeave={closeHeader} />
<Route path="/feedback" component={Feedback} onLeave={closeHeader} />
</Route>
<Route path="*" component={NoMatch} onLeave={closeHeader}/>
</Router>), document.getElementById('root'));
Based on @david-l-walsh and @bozdoz suggestions
I created a HOC that execute the
window.ga('set','page','{currentUrl})
andwindow.ga('send', 'pageview');
function and is easly used directly in the router page...this is the HOC:
and is used this way in the router page:
basic react-ga implementation with your index.js
I'm using React Router v4 and the Google Analytics Global Site Tag, which appears to be recommended at the time of writing this.
And here's my solution:
Create a component wrapped in withRouter from
react-router-dom
:Simply add the component within your router (I believe ideally after any routes that would be matched and any Switch components, because the analytics function should not be priority over your site rendering):
As stated:
So when the route changes, the
GoogleAnalytics
component will update, it will receive the new location as props, andhistory.action
will be eitherPUSH
for a new history item orPOP
to signal going backwards through the history (which I think shouldn't trigger a page view, but you can adjust the if statements incomponentWillUpdate
as you see fit (you could even trycomponentDidUpdate
withthis.props
instead, but I'm unsure which is better)).If you use hash or browser history you can do:
where ./tracking.es6
I like how Mark Thomas Müller suggests here:
In your index.js
Where your routes are:
Short, scalable and simple :)
First, in your index.js set onUpdate function to call ga
And ga.js: