Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up Google Analytics for React-Router?

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')); 
like image 851
John Fu Avatar asked Jan 17 '16 08:01

John Fu


People also ask

How does react pass data through Router?

To pass data when navigating programmatically with React Router, we can call navigate with an object. Then we can use the useLocation hook to return the object's data. const navigate = useNavigate(); navigate('/other-page', { state: { id: 7, color: 'green' } });


1 Answers

Keep a reference to your history object. i.e.

import { createBrowserHistory } from 'history';  var history = createBrowserHistory();  ReactDOM.render((     <Router history={history}>         [...] 

Then add a listener to record each pageview. (This assumes you've already set up the window.ga object in the usual manner.)

history.listen((location) => {     window.ga('set', 'page', location.pathname + location.search);     window.ga('send', 'pageview'); }); 
like image 199
David L. Walsh Avatar answered Oct 01 '22 15:10

David L. Walsh