Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 775
excurbia Avatar asked Dec 04 '25 14:12

excurbia


1 Answers

Updating from react-ga to react-ga4 worked for me.

Change the import to react-ga4 and instead of ReactGA.pageview(...) use ReactGA.send("pageview").

like image 179
Mansur Avatar answered Dec 07 '25 02:12

Mansur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!