2

So in a previous application for using Google Analytics i had this component for a <RouteChangeTracker/> this component would listen to the url change, and that would be passed to ReactGA so GA knew which page the users were on and looking at. However in react-router-dom v6 these features are missing, well, not missing but they've moved the functionality into useLocation and useNavigate but the methods attached to them have changed, im trying to refactor the component to be usuable in v6 Can someone help me here?

here is the code from the previous setup

import React from "react";
import { withRouter } from "react-router-dom";
import ReactGA from "react-ga";

const RouteChangetracker = ({ history }) => {
  history.listen((location, action) => {
    ReactGA.set({ page: location.pathname });
    ReactGA.pageview(location.pathname);
  });

  return <div></div>;
};

export default withRouter(RouteChangetracker);

I need to refactor this into a v6 setup, I tried changing out history for useLocation but it doesnt have the same effect..

Austin Howard
  • 780
  • 4
  • 10
  • 24

2 Answers2

1

This should be achievable using useLocation, there's even an example of it being implemented along with ga.

This new hook will update on each change in history, from there the pathname can be extracted.

import * as React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  let location = useLocation();

  React.useEffect(() => {
    // Google Analytics
    ga('send', 'pageview');
  }, [location]);

  return (
    // ...
  );
}
Nihil
  • 97
  • 2
  • 8
-1

i have the same problem.

in the index.html resolve with

I still haven't been able to solve it any other way

<script
      async
      src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX"
    ></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
        dataLayer.push(arguments);
      }
      gtag("js", new Date());

      gtag("config", "G-XXXXX");
    </script>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 17 '22 at 10:08