I am trying to add Google Analytics to a React Web Application.
I know how to do it in HTML/CSS/JS sites and I have integrated it in an AngularJS app too. But, I'm not quite sure how to go about it when it comes to react.
With HTML/CSS/JS, I had just added it to every single page.
What I had done with AngularJS was adding GTM and GA script to index.html and added UA-labels to the HTML divs (and buttons) to get clicks.
How can I do that with React?
Please help!
I suggest embedding the Segment script into your
index.html
, use the analytics library that is accessible on thewindow
object, and add tracking calls onto React’s event handlers:I’m the maintainer of https://github.com/segmentio/analytics-react. I recommend checking it out if you want to solve this problem by using one singular API to manage your customer data, and be able to integrate into any other analytics tool (we support over 250+ destinations) without writing any additional code.
Without using a package this is how I would do it:
In your
index.js
(in therender
method):And outside the class:
One other great library that you can check is redux-beacon.
It gets integrated very easily with react/redux application and has a great documentation for it. ReactGA is good too but with redux-beacon, you won't clutter your app code with google analytics code as it works via its own middleware.
Update: Feb 2019
As I saw that this question is being searched a lot, I decided to expand my explanation.
To add Google Analytics to React, I recommend using React-GA.
Add by running:
npm install react-ga --save
Initialization:
In a root component, initialize by running:
To report page view:
To report custom event:
More instructions can be found in the github repo
The best practice for this IMO is using react-ga. Have a look at the github rep
If you prefer not to use a package this is how it can work in a react application. Add the "gtag" in index.html
In the submit action of the login form, fire off the event