Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router-dom v6 for google analytics

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..

like image 355
Austin Howard Avatar asked Jun 11 '26 19:06

Austin Howard


1 Answers

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 (
    // ...
  );
}
like image 90
Nihil Avatar answered Jun 14 '26 15:06

Nihil