How do I add Google Analytics to React.js?
@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; |
@clarabelle
In addition to the previous steps, you'll also need to install the react-ga
package.
1
|
npm install react-ga |
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 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.