Google Analytics is a free tool provided by Google; when it comes to marketing, this tool does many things if you want to get reports about your website traffic, audience geo, user behavior, etc.
React js add google analytics script or code; Through this tutorial, you will learn how to add or integrate google analytics script in react js apps using React GA package.
How to integrate Google Analytics with React JS
Steps to add or integrate Google Analytics code or 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
Execute the following command to on terminal to create a new React project; as follows:
npx create-react-app react-ga-demo
Then open your react app on the terminal by using the following command:
cd react-ga-demo
Step 2: Add React GA Library
Execute the following command on terminal to install react ga library in your react project; as follows:
# npm npm install react-ga # bower bower install react-ga
Step 3: Insert Analytics Code
Import the ReactGA module into the App js file, this module give you access to ReactGA methods that will help you initialize the GA.
Now, have to add the Google Analytics tracking code into the initialize()
functions. So, Open and update the src/App.js file; as follows:
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;
This code is a React component that sets up and initializes Google Analytics tracking when the component is mounted.
First, it imports three modules:
Component
fromreact
is a base class for React components."./App.css"
imports a CSS file to apply styles to the component.ReactGA
is a library for integrating Google Analytics with React applications.
Next, it defines the App
component by extending the Component
class. The setGA
method initializes Google Analytics with a specific tracking code (UA-xxxxxx-xx
) and sends a page view event to the analytics server. This method is called in the componentDidMount
lifecycle method, which is called when the component is first mounted in the DOM.
Finally, the render
method returns a div
element with the className
of “App” and an h2
element with the text “React Google Analytics Example”. This is the markup that will be displayed on the page when the component is rendered. The export default
statement makes this component available for other parts of the application to use.
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