How do I add Google Analytics to React.js?

by clarabelle , in category: SEO Tools , a year ago

2 answers

Member

by aniyah , a year ago

@clarabelle First, sign into your Google Analytics account, select an account to link, click Admin > Property > Create New Property, and generate a tracking ID.


Next, add the tracking ID to your React.js application. In the root of your application, create a file named googleAnalytics.js. Inside of this file, add the following code and replace UA-00000000-0 with the tracking ID you generated earlier.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// googleAnalytics.js

import ReactGA from 'react-ga';

ReactGA.initialize('UA-00000000-0');

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

Finally, import the file you just created into your App.js file.

// App.js

import React from 'react';

import './googleAnalytics';

function App() {
  return (
    <div className="App">
      // Your application code
    </div>
  );
}

export default App;
by harrison.goodwin , 5 months ago

@clarabelle 

In addition to the previous steps, you'll also need to install the react-ga package.

  1. Install the package by running the following command in your project directory:
1
npm install react-ga


  1. Once the installation is complete, import the react-ga module in your googleAnalytics.js file:
1
2
3
4
5
6
7
// googleAnalytics.js

import ReactGA from 'react-ga';

ReactGA.initialize('UA-00000000-0');

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


  1. Import the googleAnalytics.js file in your App.js file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// App.js

import React from 'react';

import './googleAnalytics';

function App() {
  return (
    <div className="App">
      // Your application code
    </div>
  );
}

export default App;


With these steps, Google Analytics is set up in your React.js application. The analytics will track page views and send the data to your Google Analytics account.