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..
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 (
// ...
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With