'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..
Solution 1:[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>
Solution 2:[2]
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.
See this stackblitz example. When navigating either from the navigation menu or the "Go back to Home" button
let location = useLocation();
React.useEffect(() => {
console.log({ location });
}, [location]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gabriel Henrique |
Solution 2 | Nihil |