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'));
I suggest using the Segment analytics library and following the React quickstart guide to track page calls using the react-router library. You can allow the
<Route />
component to handle when the page renders and usecomponentDidMount
to invokepage
calls. The example below shows one way you could do this:I’m the maintainer of https://github.com/segmentio/analytics-react. With Segment, you’ll be able to switch different destinations on-and-off by the flip of a switch if you are interested in trying multiple analytics tools (we support over 250+ destinations) without having to write any additional code.
Given that google analytics is loaded and initialised with a tracking id.
Here is a solution for react-router version 4 using the
<Route>
component to track page views.You simply render this component inside the
<Router>
(but not as a direct child of a<Switch>
).What happens is that whenever the location prop changes it causes a re-render of this component (not actually rendering anything) that fire a pageview.
Keep a reference to your history object. i.e.
Then add a listener to record each pageview. (This assumes you've already set up the
window.ga
object in the usual manner.)For dynamically updating url on some event (like onClick etc), following can be used:
I would suggest using the excellent
react-router-ga
package that is extremely lightweight and easy to configure, especially when using theBrowserRouter
wrapper.Import the component:
import Analytics from 'react-router-ga';
Then simply add the
<Analytics>
within yourBrowserRouter
:In the React-GA documentation, they have added a community component recommended for using with React Router: https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker
Implementation
Code