React Google Analytics 4
npm install react-ga4``jsreact-ga
// Simply replace with react-ga4 and remove ReactGA.pageview()`
// import ReactGA from "react-ga";
import ReactGA from "react-ga4";
`bash`
npm i react-ga4
`js
import ReactGA from "react-ga4";
ReactGA.initialize("your GA measurement id");
`
More example can be found in test suite
`js
// Multiple products (previously known as trackers)
ReactGA.initialize([
{
trackingId: "your GA measurement id",
gaOptions: {...}, // optional
gtagOptions: {...}, // optional
},
{
trackingId: "your second GA measurement id",
},
]);
// Send pageview with a custom path
ReactGA.send({ hitType: "pageview", page: "/my-path", title: "Custom Title" });
// Send a custom event
ReactGA.event({
category: "your category",
action: "your action",
label: "your label", // optional
value: 99, // optional, must be a number
nonInteraction: true, // optional, true/false
transport: "xhr", // optional, beacon/xhr/image
});
`
#### ReactGA.initialize(GA_MEASUREMENT_ID, options)
| Parameter | Notes |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| GA_MEASUREMENT_ID | string Required |string
| options.nonce | Optional Used for Content Security Policy (CSP) more |boolean
| options.testMode | Default false |string
| options.gtagUrl | Default https://www.googletagmanager.com/gtag/js |object
| options.gaOptions | Optional Reference |object
| options.gtagOptions | Optional |
#### ReactGA.set(fieldsObject)
| Parameter | Notes |
| ------------ | ----------------- |
| fieldsObject | object Required |
#### ReactGA.event(name, params)
This method signature are NOT for UA-XXX
| Parameter | Notes |
| --------- | ----------------------------------------------------------------------------------------------------------------------------- |
| name | string Required A recommended event or a custom event |object
| params | Optional |
#### ReactGA.event(options)
| Parameter | Notes |
| ---------------------- | ----------------------------------- |
| options | object Required |string
| options.action | Required |string
| options.category | Required |string
| options.label | Optional |number
| options.value | Optional |boolean
| options.nonInteraction | Optional |'beacon'\|'xhr'\|'image'
| options.transport | Optional |
#### ReactGA.send(fieldsObject)
| Parameter | Notes |
| ------------ | ----------------- |
| fieldsObject | object Required |
#### ReactGA.gtag(...args)
#### ReactGA.ga(...args)
`js
import { ReactGAImplementation } from "react-ga4";
class MyCustomOverriddenClass extends ReactGAImplementation {}
export default new MyCustomOverriddenClass();
``
Use Google Analytics Debugger Chrome Extension to see logs
MIT