Spluli
Spluli

Reputation: 69

ReactGA BrowserRouter Uncaught TypeError: undefined (reading 'pathname') error and/or useLocation error

I try to install Google Analytics, but then my site won't load.

I had the error: Uncaught Error: useLocation() may be used only in the context of a <Router> component. So I added <Routes> to index.js

Index.js:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { HelmetProvider } from "react-helmet-async";
import { Router } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <Router>
    <HelmetProvider>
      <App />
    </HelmetProvider>
  </Router>

);

My App.js:

import React from "react";
import ReactGA from "react-ga";
import InitializeReactGA from "./components/helper/googleAnalytics";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useLocation,
} from "react-router-dom";
import { useEffect } from "react";

...

const TRACKING_ID = "A-1234567890"
ReactGA.initialize(TRACKING_ID );

function usePageViews() {
    let location = useLocation();
    useEffect(() => {
        InitializeReactGA(ReactGA);
        ReactGA.set({ page: location.pathname });
        ReactGA.pageview(location.pathname);
    }, [location]);

function App() {
  usePageViews();

  return (
    <>
      <Router>
        <Navbar />
        <Routes>
          <Route path="/"                            element={<Home                          />} />
          <Route path="/abouts"                      element={<AboutUs                       />} />
          .....
        </Routes>
        <Footer />
      </Router>
    
    </>
  );
}

GA helper:


function InitializeReactGA(ReactGA) {
  if (!window.GA_INITIALIZED) {
    ReactGA.initialize("MANDO_GA");  //just copied that, don't know what MANDO_GA is
    window.GA_INITIALIZED = true;
  }
}

export default InitializeReactGA;

now I get the error: components.tsx:197 Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')

Upvotes: 0

Views: 122

Answers (2)

Spluli
Spluli

Reputation: 69

So i tried some stuff because of @Miguel Caro

index.js:


<Router>
    <HelmetProvider>
      <App />
    </HelmetProvider>
  </Router>

App.js:


function App() {
  usePageViews();

  return (
    <>
       {/* DELETED!  Router  DELETED! */}
        <Navbar />
        <Routes>
          <Route path="/"                            element={<Home                          />} />
          <Route path="/abouts"                      element={<AboutUs                       />} />
          .....
        </Routes>
        <Footer />
      {/* DELETED! /Router  DELETED!*/}
    
    </>
  );
}

now it works

Upvotes: 0

Miguel Caro
Miguel Caro

Reputation: 298

that happen when you use the useLocation outside of the router

Upvotes: 1

Related Questions