React JS Integrate Google Analytics (GA4) Script Tutorial

React JS Integrate Google Analytics (GA4) Script Tutorial

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

Recommended React Js Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *