Add google analytics to your react website

a month ago2 minutes read

Google Analytics stands as a robust web analytics solution, delivering invaluable insights into the traffic on your website and the behavior of its users. The integration of Google Analytics into your Next.js application empowers you to monitor and analyze user interactions, gauge the effectiveness of marketing campaigns, and base your decisions on data-driven insights. In the following guide, we will delve into the process of configuring Google Analytics (using gtag.js) for your Next.js application.

Analytics Account setup

  • First visit analytics.google.comGoogle Analytics and signup using your google account
  • Click on Start Measuring to start and create your account after filling up all the details
  • Fill up the form and add a new property for your website

Creating Property

  1. Give it a name and click next img

  2. Select Category and team size img2

  3. Select Objectives img3

  4. Select Web and copy the measurement id img4 img5

Code

Now in your react project create a component named Analytics.jsx and put the code in it. Berfore that install react-ga4 using npm or yarn

npm i react-ga4
Analytics.jsx
jsimport { useEffect } from "react"
import ReactGA from "react-ga4"

const Analytics = () => {
  useEffect(() => {
    ReactGA.initialize("Measurement ID Here")
  }, []);
  
  return null
};

export default Analytics

After the component has been created import it in your App component or main.jsx file and use it lie <Analytics />. After all these steps done open the project in your browser and see data updated on analytics dashboard.

ShahriyarAlam

Copythight © All Rights Reserved.