0

I am using react-router-dom V4.3.1. I would like to implement web analytics to my react application on every page/location change. Can you please provide any solution?

Ajeet Shah
  • 12,593
  • 7
  • 43
  • 60
Mahesh
  • 31
  • 5
  • https://stackoverflow.com/questions/41911309/how-to-listen-to-route-changes-in-react-router-v4 – Nikita Madeev May 27 '20 at 14:31
  • I have already developed an application using redux. It is difficult to add logic on top of it. I need a solution to make changes at one place. Anyway, I got workaround for my problem. Thank all for the comments – Mahesh May 28 '20 at 05:58

2 Answers2

0

You can listen to current location changes using history.listen:

import React, { useEffect } from 'react'
import history from '../routes/history'

export default function App() {

  useEffect(() => {
    // Listen for changes to the current location.
    const unlisten = history.listen((location, action) => {
      // location is an object like window.location
      console.log(
        `The current URL is ${location.pathname}${location.search}${location.hash}`
      )
      console.log(`The last navigation action was ${action}`)
    })
    return function cleanup() {
      // To stop listening, call the function returned from listen().
      unlisten()
    }
  }, [])

  return (
    <div>
      Hello, World!
      {/* <MyRoutes /> */}
    </div>
  )
}

There are various ways to get access to history object depending on your react-router version or routing setup.

You can use withRouter HOC, or createBrowserHistory() from history package if have setup routes using Router. For those using react-router v5, useHistory hook can also be used to get history object.

If you are using react version prior to 16.8, you can use componentDidMount and componentWillUnmount instead of useEffects.

Ajeet Shah
  • 12,593
  • 7
  • 43
  • 60
0

The Workaround is as shown below :

const invokeMyWebAnalyticProvider = () => {
  //Code to invoke your analytics
}
const invokeWebTracker = () => {
  if(typeof window.localStorage.getItem('currentPage') !== 'undefined'){
    if(window.localStorage.getItem('currentPage') !== window.location.pathname){
      window.localStorage.setItem('currentPage', window.location.pathname);
      invokeMyWebAnalyticProvider();
    }
  }
}
const Router = () => (
  <MainWrapper>
      {invokeWebTracker()}
      <Switch>        
        <Route exact path='/' component={Login} />
        .
        .
        .
      </Switch>    
  </MainWrapper>
);

With this code, I can track the page/location changes in Web Analytics. But it can't be used for event tracking. If you need event tracking need to add the code in each component.

Can anyone validate this solution?

Mahesh
  • 31
  • 5