Search code examples
google-analytics-4react-ga

Google analytics user property react-ga4


I'm using react-ga4. I wonder how i could send user properties using this library and set it up in the google analytics panel as I think that i'm doing something wrong.

This is how i initialize ReactGA4

ReactGA.initialize(
      [
        {
          trackingId: id,
          gaOptions: {
            role: userRole,
          }
        },
      ]
)

any suggestion?


Solution

  • It depends what user properties that you want to send. You can send custom user properties that not reserved by Google.

    For example, I want to send account_verified with boolean value and name with string value in user property. You can use ReactGA.gtag(...args) in this library, and then you can use it directly or put it into utils/analytics.js and wrap it to export function with parameter, so you can use it whenever it needs.

    import ReactGA from "react-ga4";
    
    
    ReactGA.gtag("set", "user_properties", {
       account_verified: true,
    });
    
    ReactGA.gtag("set", "user_properties", {
       name: "John",
    });
    

    or

    import ReactGA from "react-ga4";
    
    
    export const setAccountProperty = (value: boolean) => {
      ReactGA.gtag("set", "user_properties", {
        account_verified: value,
      });
    };
    
    export const setNameProperty = (value: string) => {
      ReactGA.gtag("set", "user_properties", {
        name: value,
      });
    };
    

    After that, you can check in your Google Analytics in DebugView directly to ensure your user properties works well.