Reputation: 491
I'm using react-ga for my google analytics, react-router for routing, and my navbar uses push in order to transfer between pages.
Although I have tried to change it to <Link>
and it did not solve the problem.
Here's a relevant piece of my app.js file:
function App() {
useEffect(() => {
ReactGA.initialize("<myCode>");
ReactGA.pageview(window.location.pathname + window.location.search);
}, []);
return (
<div className="App">
<Router>
<Switch>
<Route exact path="/" component={Homepage} />
<Route path="/register" component={Register} />
The right page will be updated when I type the address in the address bar of my browser, or even switch the page using the navbar and then hit "refresh". But it would not be updated if I only move pages through the navbar.
I do understand that this issue is most likely because this line:
ReactGA.pageview(window.location.pathname + window.location.search);
Is probably not executed when I move between pages, but not sure what would be the best practice to fix it.
This is a relevant piece of my navbar:
<div
className={styles.navOption}
onClick={() => {
this.movePage("/"); // <--- Calls this.props.history.push
}}
>
home
</div>
Upvotes: 1
Views: 1240
Reputation: 94
You need to put the useEffect in every component you want analytics for, and not in the main app component, since you want different analytics for each module, and because it is the wrong place to write it since the App component renders only once in this case, so the useEffect you wrote won't happen each route you enter.
Upvotes: 2