Blog>
Snippets

Logging Route Transitions

Provide an example of how to log route transitions for analytic purposes by implementing an interceptor that logs every route change.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { useEffect } from 'react';

class AnalyticsService {
  static logPageView(url) {
    console.log(`Page view logged: ${url}`); // Replace with actual analytics service
  }
}

function App() {
  useEffect(() => {
    // Log initial page load
    AnalyticsService.logPageView(window.location.pathname);
  }, []);

  return (
    <Router>
      <Route render={({ location }) => {
        // Log every route change
        AnalyticsService.logPageView(location.pathname);
        return null;
      }} />
      <Switch>
        {/* Define your routes here */}
        <Route path='/home' component={HomePage} />
        <Route path='/about' component={AboutPage} />
        //... other routes
      </Switch>
    </Router>
  );
}
This code sets up a React Router and logs every route transition. It imports the necessary components from 'react-router-dom'. An `AnalyticsService` class with a static `logPageView` method is created to handle the logging, which you would replace with your actual analytics service. The `App` component sets up the router with a special route that uses the `render` prop to execute the logging side-effect on every route change. It also logs the initial page load using a React `useEffect` hook.