Reputation: 173
I'm trying to track each page but google only registers a view each time I click the refresh button. Not when iv'e routed to a new path. Anyone got an Idea on how to make this work?
import React, {useEffect} from 'react';
import { BrowserRouter, Switch, Route } from "react-router-dom";
import OurWork from "./ourWork/ourWork"
import Home from "./home/Home"
import Packages from "./packages/Packages"
import Contacts from "./contact/Contact"
import ReactGA from 'react-ga'
import createHistory from 'history/createBrowserHistory'
const Routes = () => {
const {
ContactPage
} = Contacts();
const history = createHistory()
history.listen(location => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
useEffect(() => {
ReactGA.pageview(window.location.pathname + window.location.search)
}, [history])
return(
<BrowserRouter history={history}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/ourwork" exact component={OurWork} />
<Route path="/packages" exact component={Packages} />
<Route path="/Contact" exact component={ContactPage} />
</Switch>
</BrowserRouter>
)
}
export default Routes;
Upvotes: 1
Views: 2011
Reputation: 1213
Looks like the same issue which is described here. Try to change <BrowserRouter history={history}>
to <Router history={history}>
and import Router
from the "react-router-dom"
, like this:
import React, {useEffect} from 'react';
import { Router, Switch, Route } from "react-router-dom";
import OurWork from "./ourWork/ourWork"
import Home from "./home/Home"
import Packages from "./packages/Packages"
import Contacts from "./contact/Contact"
import ReactGA from 'react-ga'
import createHistory from 'history/createBrowserHistory'
const Routes = () => {
const {
ContactPage
} = Contacts();
const history = createHistory()
history.listen(location => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
useEffect(() => {
ReactGA.pageview(window.location.pathname + window.location.search)
}, [history])
return(
<Router history={history}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/ourwork" exact component={OurWork} />
<Route path="/packages" exact component={Packages} />
<Route path="/Contact" exact component={ContactPage} />
</Switch>
</Router>
)
}
export default Routes;
Upvotes: 2