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'));
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' } });
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'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With