Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save collegeimprovements/10f0ea191d1271f3a814147913db69ab to your computer and use it in GitHub Desktop.
Save collegeimprovements/10f0ea191d1271f3a814147913db69ab to your computer and use it in GitHub Desktop.
Google Analytics
March 20, 2019 at 6:16pm (Edited 4 months ago)
I'm implementing Google Analytics to Reach Router running inside a React Static app (hence checking if the document exists).
This seems to be working, but if I console.log the pageview attributes, they get logged twice on each page visit. What's causing this?
// My Analytics component
import React from "react";
import { Location } from "@reach/router";
import ReactGA from "react-ga";
//
export default ({ children, id }) => {
if (typeof document === "undefined" || !id) {
return children;
}
ReactGA.initialize(id);
return (
<Location>
{({ location }) => {
ReactGA.pageview(location.pathname + location.search + location.hash);
console.log(location.pathname, location.search, location.hash);
return children;
}}
</Location>
);
};
EDIT:
In case someone else is implementing the same, I was having issues with the page title from the previous path showing up on the analytics reports. This is due to React Helmet title update lag (GitHub issue). Ended up solving this by also updating the title with pure Javascript as follows:
if (typeof window !== "undefined") window.document.title = title;
Again checking for the presence of window as I'm using React Static.
Like
1
hi
@hellojere
- thanks for this!!
Are you finding the double entries in the google analytics reports as well as in console? Does it seem to be reporting accurately otherwise?
Thanks again,
m
Edited
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment