Learn business growth with Google Analytics 4 Forums Google Analytics 4 Integrating Google Analytics 4 with Inertia React in Laravel 10

  • Integrating Google Analytics 4 with Inertia React in Laravel 10

    Posted by Quinn on 11 July 2022 at 4:19 pm

    Hey pals, so I’ve been working with laravel 10, which comes built in with reactjs and inertia – plus SSR – for my newest app.

    I’ve decided to use this react-ga4 package, but honestly, I’m drawing a blank. Where exactly do I put the initialization code in the app root?

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

    Here’s how my app.jsx currently looks like:

    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) => <span class="hljs-subst">${title}</span> - <span class="hljs-subst">${appName}</span>,
        resolve: (name) => resolvePageComponent(./Pages/<span class="hljs-subst">${name}</span>.jsx, import.meta.glob('./Pages/**/*.jsx')),
        setup({ el, App, props }) {
            const root = createRoot(el);
    
            root.render(<App {...props} />);
        },
        progress: {
            color: '#4B5563',
        },
    });
    

    Any thoughts on where this initialize and send code from react-ga4 package should go?

    Lucas replied 11 months, 1 week ago 3 Members · 2 Replies
  • 2 Replies
  • Cameron

    Member
    17 May 2023 at 9:55 am

    Sure thing, mate! This is pretty straightforward. Just import the react-ga4 package at the top of your file:

    `javascript
    import ReactGA from ‘react-ga4’;
    `

    Then, inside the setup function of createInertiaApp, you can initialize it with your Google Analytics measurement ID:

    `javascript
    ReactGA.initialize(“your GA measurement ID”);
    `

    So, you’ll actually give Google Analytics a heads up when your app starts up. Pretty neat, huh? It’s alright if you didn’t catch it at first, it’s just a matter of seeing it once and you’ll know for next time. Cheers!

  • Lucas

    Member
    19 May 2023 at 3:22 am

    You can put the initialization code for your react-ga4 package in the block that sets up your application (setup section) in your app.jsx file. This way, the package and its functions will be loaded and available to use just as your app starts to run. The initialization code helps to connect your app with the Google Analytics tracking system using your unique ID, so make sure it runs before any other interactions occur in your app.

Log in to reply.