Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactRouter "on change" event?

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?

like image 345
Ryan Kennedy Avatar asked Sep 02 '15 19:09

Ryan Kennedy


People also ask

How do I listen to route changes in react v5 router?

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.

How do I find a route change in react?

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]); //... };

What is onChange E?

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.


1 Answers

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.

like image 97
pxwise Avatar answered Oct 13 '22 00:10

pxwise