I want to install an analytics handler on my single page app, and would like to capture every route change under the main route. I recognize that ReactRouter offers an onEnter
route event; however, this would require me to separately install the handler on each route. I could create a subclass of Route that automatically has onEnter
populated, but then I would not be able to override onEnter
and still keep the analytics tracking handler.
What would be the best way to listen for any change within a given root Route?
Use your router and pass your history object to it. In a component you want to listen to location changes on, import your history object and invoke the listen callback as you did previously. import history from '../myHistory'; ... useEffect(() => { const unlisten = history.
To detect route change with React Router, we can use the useLocation hook. import { useEffect } from "react"; import { useLocation } from "react-router-dom"; const SomeComponent = () => { const location = useLocation(); useEffect(() => { console. log("Location changed"); }, [location]); //... };
The onChange event in React detects when the value of an input element changes. Let's dive into some common examples of how to use onChange in React. Add an onChange Handler to an Input. Pass an Input Value to a Function in a React Component. Storing an Input Value Inside of State.
You can use the react-router willTransitionTo static function to detect a route change and emit the transition.path
in your ga()
function call, like so:
var App = React.createClass({
mixins: [Router.State],
statics: {
willTransitionTo: function(transition, params, query, props) {
ga('send', 'pageview', {'page': transition.path});
}
},
render: function() {
return (
<div>
<RouteHandler />
</div>
);
}
});
A more complete example can be seen in this answer.
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