Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track pageviews on React

So basically the problem i have is that my site is using reactjs so it doesn't reload and i need to detect the change on the URL in order to send a new pageview to Google Analytics. Has anyone deal with this before?


EDIT: Maybe i was a little unclear, im using Google Tag Manager and i have no control over the code on the page but i can request for dataLayers. The obvious solution is to ask for a dataLayer when the page changes but since i would like to avoid doing this i was strictly asking if anyone knows a way to detect this kind of changes on the DOM from GTM.

like image 449
Marco Avatar asked Jan 19 '18 18:01

Marco


3 Answers

For single page apps, you can track 'virtual' pageviews like given in the docs:

When the page changes, do

ga('set', 'page', '/new-page.html');

After this point, if your do a 'send', it will track this page.

ga('send', 'pageview');

I'd suggest you use something like react-ga for doing it a little more conveniently, it has functions like

ReactGA.pageview('/about/contact-us'); and ReactGA.modalview('/about/contact-us');

like image 165
Palash Karia Avatar answered Oct 18 '22 04:10

Palash Karia


You need to look for all the paths using a Route like this,

<Route path="/" component={updateTracking} />
<Switch>
   ..... //further actual routes
</Switch>

and then send the pageview using the global Google Analytics (ga) method (accessible through the window object) using window.location.pathname

const updateTracking = () => {
   window.ga('send', 'pageview', {
      page: window.location.pathname
   });
}

Note: You need to put the tracking code you got from Google Analytics in the main HTML (index.html) for it all to work.

like image 23
Nilesh Singh Avatar answered Oct 18 '22 05:10

Nilesh Singh


Alternatively, you can listen for createBrowserHistory changes and send a pageview event.

import { createBrowserHistory } from 'history'

const history = createBrowserHistory()

history.listen(() => {
    window.ga('send', 'pageview', {
      page: window.location.pathname
    })
  }
)
like image 2
Won Jun Bae Avatar answered Oct 18 '22 04:10

Won Jun Bae