'Google analytics with react is not working
I am using google analytics in my react project and it doesn't show any active users even when I am online. I have tried different approaches that I found online but none seem to work. I have only tried it on localhost and not on a deployed website but I think it should still work.
Here is my code.
My app.js
import React, { Suspense, useEffect } from "react";
import "./App.css";
import IntroPage from "./containers/IntroPage/IntroPage";
import Layout from "./containers/Layout/Layout";
import { Switch, Route, Redirect, withRouter } from "react-router-dom";
import Spinner from "./Components/UI/Spinner/Spinner";
import ReactGA from "react-ga";
const Contact = React.lazy(() => import("./Components/Contact/Contact"));
const trackingId = "UA-171033255-1";
ReactGA.initialize(trackingId);
function App() {
useEffect(() => {
ReactGA.pageview(window.location.pathname + window.location.search);
}, []);
return (
<div className="App">
<Layout>
<Switch>
<Route
path="/contact"
render={() => (
<Suspense
fallback={
<div className="Fallback">
<Spinner />
</div>
}
>
<Contact />
</Suspense>
)}
/>
<Route path="/" component={IntroPage} />
<Redirect to="/" />
</Switch>
</Layout>
</div>
);
}
export default withRouter(App);
What am I doing wrong here?
Solution 1:[1]
have you included the cdn link and js for google analyctics in the head of html?
Solution 2:[2]
Have you tried adding the tracking code inside <head> in index.html (Admin -> Property -> Tracking code)?
Solution 3:[3]
Since you are using empty dependencies array in useEffect your code gets executed only once, when <App/> rendered. So you are not sending pageviews on route change.
You need to put pageview-related code before your App component, right after ReactGA initialization. It's a usage example from docs.
Solution 4:[4]
I had a similar issue try disabling your ad block if you have it active and put the ReactGA.initialize inside the useEffect
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fharris |
| Solution 2 | BigMugOfCoffee |
| Solution 3 | Jenia Enakin |
| Solution 4 | Hazem Ben Abdelhafidh |
