In this article, we'll show you how to make sure that the URL changes are pushed into Mouseflow to create individual Page Views.

Setup of URL change tracking

Please follow these steps to manually set up tracking of URL changes:

1. Import Reat-Router

In this tutorial we are working with react-router

You will want to have the BrowserRouter component wrapping your entire application like so


index.jsx

import React from 'react' 
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'

import Root from './Root'

ReactDOM.render(
<BrowserRouter>
<Root />
</BrowserRouter>,
document.getElementById('root')
)

2. Listening for route changes

You can use hooks to listen for route changes

Root.jsx

import React, { useEffect } from 'react' 
import App from './components/App'

import { useHistory } from 'react-router-dom' const

Root = () => {
const history = useHistory()

useEffect(() => {
return history.listen((location) => {
console.log(`You changed the page to: ${location.pathname}`)
})
},[history])

return (
<App />
)
}

3. Talking to the Mouseflow API

Mouseflow uses an array _mfq in the browser to pass various meta-data to the Mouseflow server. One of the things Mouseflow looks for in this array is new page views. Now that we are listening to the new page views on our React app, we can simply push a key-value pair into this array each time the route changes. This virtually makes Mouseflow recognize new page views.

useEffect(() => { 
return history.listen((location) => {
window._mfq.push(['newPageView', location.pathname]);
})
}, [history])

Congratulations, your React application should now be submitting all pageviews to Mouseflow as would any traditional HTML website.

Did this answer your question?