Learn business growth with Google Analytics 4 Forums Google Analytics 4 Creating Custom Events with Custom Parameters in GA4

  • Creating Custom Events with Custom Parameters in GA4

    Posted by Isaac on 28 January 2023 at 4:18 pm

    Hey there!

    I’m in the middle of a project where I need to create a custom event with specific parameters for GA4 (Google Analytics). This is how I want it to look:

    `
    {
    “event_name”: “game_over”,
    “action”: “message shown”,
    “label”: {the current url},
    “data”: {some JSON object data}
    }
    `

    That’s going to be sent over from my React site to the current Google Analytics project.

    So far, I’ve looked through the GA4 docs and Googled a bunch, but all I seem to find is stuff around ‘Universal Analytics’, with nothing much on GA4. There was one article I found, [this one right here](https://www.delasign.com/blog/custom-ga-event-reactjs-gatsbyjs/), which was handy for creating a custom event, but I’m still stuck on the custom params part.

    I’m still on the hunt for any leads, but if you have any ideas or have done something like this before, it would be super cool if you could give me some tips!

    PS: To those of you with 1500 or more stack overflow points, could you add the GA4 (or ga4) tag to my question? For some reason, I’m not permitted to. If you could strike out this sentence once that’s done, that’d be great too! Cheers!

    Lily replied 1 year, 3 months ago 2 Members · 1 Reply
  • 1 Reply
  • Lily

    Member
    6 June 2023 at 11:41 pm

    Yo!

    I’ve cracked it! Basically, you was on the right track with that article you found (this one: [custom event GA4](https://www.delasign.com/blog/custom-ga-event-reactjs-gatsbyjs/)), you just need to tweak it a bit.

    In **step 2**, switch up the ‘TrackGoogleAnalyticsEvent’ method like this:

    `
    const TrackGoogleAnalyticsEvent = (
    category,
    event_name,
    label,
    data
    ) => {
    console.log(“GA event:”, category, “:”, event_name, “:”, label);

    let event_params = {
    category,
    label,
    …data
    };
    // This will send your GA4 Event
    ReactGA4.event(event_name, event_params);
    };
    `

    Then, on the client side, just pop the following code in:

    `
    TrackGoogleAnalyticsEvent(
    “game_over”,
    “message shown”,
    window.location.pathname + window.location.search,
    { id: 1234, username: “john” }
    );
    `

    Here’s a little tip: you can stuff as many parameters as you like into the JSON object.

    Take a look at the [‘react-ga4’ package](https://github.com/codler/react-ga4) for more deets.

Log in to reply.