-1

I have a react SPA and need to add tracking when react router loads/changes page so the tracking knows about all the goodness of what the user is doing. I don't even know where to start.

I tried loading the tracking script in the index.html and then add the tracking object in the componentDidMount function but that isn't working as that is not happening on page load.

What do I need to do?

saunders
  • 969
  • 4
  • 14
  • 25

1 Answers1

0

if you are using redux as well:

set up react-router-redux by following the basic setup guide

Then, you will be able to set up a simple middleware that hooks into routing. Define middlewares/routing.js like so:

// https://github.com/reactjs/react-router-redux#location_change
import { LOCATION_CHANGE } from 'react-router-redux';

export default function routeTracker(store) {
  return next => action => {
    if (action.type === LOCATION_CHANGE) {
      // whatever action you want here.
    }
    next(action);
  }
}

Now import and apply this middleware where your store is created

import routeTracker from '../middlewares/router';
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from '../reducers';

export default function createStore(initialState) {
  // ...
  const enhancer = compose(applyMiddleware(routeTracker));
  const store = createStore(rootReducer, initialState, enhancer);
  return store;
}
corvid
  • 10,733
  • 11
  • 61
  • 130