mrpbennett
mrpbennett

Reputation: 1956

GA v4 in a React Vite project

What's the best way to add Google Analytics to a Vite React project? I have added the gtag.js script into the index.html file within the Vite project. It does track users in Real Time but doesn't seem to track anything else. This makes me think the code should be in App.jsx instead...

Because when I go to GA I am getting the message saying there is No data received from my website yet.

I have looked into react-ga but this seems to only work with UA-XXX tags where as I am using GA v4 which uses IDs of G-XXXX

Has anyone added a v4 GA tag into a React project?

Update

Just found https://www.npmjs.com/package/react-ga4

This is how I have it now...

import React from 'react'
import ReactGA from 'react-ga4'
import {Helmet} from 'react-helmet'
import Footer from './components/base/Footer'
import Header from './components/base/Header'
import Form from './components/Form'
import Table from './components/Table'

ReactGA.initialize('G-XXXXXXX')
ReactGA.send('pageview')

function App() {
  return (
    ...

But still getting the message "No data received from your website yet." in GA

Upvotes: 2

Views: 5875

Answers (1)

husayt
husayt

Reputation: 15139

It's best to use a vite plugin for that. Currently Vite-plugin-radar is available and it supports 7+ analytics providers ( Google Analytics, Google Tag Manager, Facebook Pixel, Linkedin Insight, Yandex Metrica, Baidu Tongji and Microsoft Advertising)

Another advantage with vite plugins is that mostly they are framework agnostic, so you can use them with Vue, React, Svelte or other vite supported frameworks.

Upvotes: 4

Related Questions