In this tutorial, you will learn how to add or integrate Google Analytics (GA4) script in react js apps using React GA package.
How to Integrate Google Analytics (GA4) in React JS
Steps to add Google Analytics script in React JS app:
- Step 1: Create React Project
- Step 2: Add React GA Library
- Step 3: Insert Analytics Code
- Step 4: Start Application
Step 1: Create React Project
Run the following command to on cmd to create a new React project; as follows:
npx create-react-app react-ga-demo
Navigate to your react app by using the following command:
cd react-ga-demo
Step 2: Install React GA Library
Run the following command on cmd to install the react ga library in your react project:
# npm
npm install react-ga
# bower
bower install react-ga
Step 3: Add GA4 Analytics Code
Import the ReactGA module into the App.js
file:
import { Component } from "react";
import "./App.css";
import ReactGA from 'react-ga';
class App extends Component {
setGA = () => {
ReactGA.initialize('UA-xxxxxx-xx');
ReactGA.pageview('Init page view');
};
componentDidMount(){
this.setGA();
}
render() {
return (
<div className="App">
<h2>React Google Analytics Example</h2>
</div>
);
}
}
export default App;
Step 4: Start Application
Again open the command line screen and type the following command that will start the react app; as follows:
npm start