I am trying to add Google Analytics with react-router v5 StaticRouter in my React SSR app as suggested in How to use Google Analytics with React?. I understand createBrowserHistory doesn't work so thought I will use createMemoryHistory. Seems the removed createMemoryHistory in v4? I would try to listen to route change in but couldn't figure out how to do that with SSR? Or I could write a HOC and fix it. But it seems this a bit cleaner and easier way to do it.
Now to achieve something like this, how do I do it?
import ReactGA from 'react-ga';
import { createMemoryHistory } from 'history';
ReactGA.initialize('UA-*********-1');
const history = createMemoryHistory();
history.listen(location => {
console.log('location', location);
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
function NotFound() {
return <h1>Oops, nothing here!</h1>;
}
function App() {
return (
<Switch>
{routes.map(({ path, component, isPublic, exact }) => (
isPublic ?
<Route
key={path}
exact={exact}
path={path}
component={component}
history={history}
/>
:
<ProtectedRoute
isLoggedIn={user}
key={path}
path={path}
component={component}
exact={exact}
public={false}
history={history}
/>
))}
<Route component={NotFound} />
</Switch>)
);
}