Adding Google Analytics to React

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:

import ReactGA from 'react-ga';
ReactGA.initialize('Your Unique ID');

To report page view:

ReactGA.pageview(window.location.pathname + window.location.search);

To report custom event:

ReactGA.event({
  category: 'User',
  action: 'Sent message'
});

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


Without using a package this is how I would do it:

In your index.js (in the render method):

    {/* Global site tag (gtag.js) - Google Analytics */}
    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"
    />
    <script>{injectGA()}</script>

And outside the class:

const injectGA = () => {
  if (typeof window == 'undefined') {
    return;
  }
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    window.dataLayer.push(arguments);
  }
  gtag('js', new Date());

  gtag('config', 'YOUR_TRACKING_ID');
};

If you prefer not to use a package this is how it can work in a react application. Add the "gtag" in index.html

<!-- index.html -->

<script>
            window.dataLayer = window.dataLayer || [];
            function gtag() {
                dataLayer.push(arguments);
            }
            gtag("js", new Date());

            gtag("config", "<GA-PROPERTYID>");
        </script>

In the submit action of the login form, fire off the event

window.gtag("event", "login", {
            event_category: "access",
            event_label: "login"
        });