Search code examples
reactjslaravelgoogle-analyticsgoogle-analytics-4inertiajs

How to implement Google Analytics 4 in Laravel 10 Inertia Reactjs?


I am using laravel 10 built in reactjs and inertia with SSR on my new application.

I am trying to implement using this react-ga4 package.

The problem is I have no idea where to put initialize code in app root

ReactGA.initialize("your GA measurement id");

In app.jsx which comes from laravel looks like this

import './bootstrap';
import '../css/app.css';

import { createRoot } from 'react-dom/client';
import { createInertiaApp } from '@inertiajs/react';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';

const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.glob('./Pages/**/*.jsx')),
    setup({ el, App, props }) {
        const root = createRoot(el);

        root.render(<App {...props} />);
    },
    progress: {
        color: '#4B5563',
    },
});

Where should I put the initialize and send code from react-ga4 package?


Solution

  • add below to import the react-ga4 lib

    ...

    import ReactGA from 'react-ga4';
    
    
    
    createInertiaApp({
        title: (title) => `${title} - ${appName}`,
        resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.glob('./Pages/**/*.jsx')),
        setup({ el, App, props }) {
            // add this for the ga4 initialization
            ReactGA.initialize("your GA measurement id");
    
            const root = createRoot(el);
    
            root.render(<App {...props} />);
        },

    ...