I'm trying to set up Google Analytics 4 on my react site. Previously I used react-ga, but this library doesn't support Google Analytics 4 yet. I pasted the GA4 tag directly into the index.html file without an external library. What additional code do I need to add to get GA4 to work with react router?
Thanks in advance!
You can call gtag directly. Just put the global site tag code in your index.html <head>.
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
I was facing the same issue today and ended up pulling out the react-ga package and going this route. I saved the withTracker.js piece from the react-ga demo code and modified it like below.
export default function withTracker(WrappedComponent, options = {}) {
const trackPage = (page) => {
window.gtag('send', 'page_view', {
page_location: window.location.href,
page_path: window.location.pathname
});
};
...
You can also checkout the npm package ga-4-react:
https://www.npmjs.com/package/ga-4-react
You should be able stop using react-ga and just insert the global script tag in index.html as Cameron mentioned. Keep in mind you'll likely need to ensure that your app is updating both the window.location and document.title for GA4 work as desired.
Google's docs mention:
"When a pageview is sent to Analytics, the default page parameter values are used, unless modified. This means you do not need to modify page_title or page_location parameters if updates to window.location (e.g. via the History API) and document.title are made prior to the event being sent.".
I have a simple single page application and wasn't receiving detailed page view data until I updated the title AND location at each render.
Background: There are 2 types of Google Analytics properties: Universal Analytics (UA-xxxxxxxxx-x) which is deprecated with the end of life on 2023.07.01 and Google Analytics 4 property (G-xxxxxxxxxx) which is the replacement.
The simplest way to get started is to follow Google's guide: include gtag on the page and use it as window.gtag. This method works for both old and new tags and there's even TypeScript support via #types/gtag.js. The script can be loaded async as recommended.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
<script
async
src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxxxx" >
</script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-xxxxxxxxxx')
</script>
<!-- ... -->
</head>
<body>
<!-- ... -->
</body>
</html>
Keep in mind that Google Analytics does automatic page tracking, but this will not work for every use case. For example, hash and search parameter changes are not tracked. This can lead to a lot of confusion. For example, when using HashRouter or anchor links the navigation will not be tracked. To have full control over page view tracking you can disable automatic tracking. See for a detailed explanation: The Ultimate Guide to Google Analytics (UA & GA4) on React (Or Anything Else
Manual page tracking: https://stackoverflow.com/a/63249329/2771889
You can see this working in cra-typescript-starter where I'm also setting the tag from an env var.
No additional code is needed, just paste that tag into the index.html and Google Analytics will track all your urls.
Related
I am using a React.js app in a Cordova framework.
As the docs are not really clear, I would like to understand how to call a Branch.io listener in a my app, so that I can capture where the Branch.io link was clicked, by whom and what exact URL was clicked. There must be a way to call the Branch.io events from React itself (otherwise, how can you be listening to the event inside the app?). I tried the following in my index.js file but was not successful because the build of the React app failed (as cordova is only available during runtime).
import {Branch} from "branch-cordova-sdk"
Any help would be appreciated! Thanks in advance!
For anybody else arriving at this page:
If you are trying to generate and access branches from Branch.io in your React.js app (not React native) and you have embedded it into a Cordova app, you have to follow these documentation: https://help.branch.io/developers-hub/docs/web-basic-integration
As quick bullet points:
You have to call the branch in your index.html file, as mentioned in the docs:
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script>
// load Branch
(function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener applyCode autoAppIndex banner closeBanner closeJourney creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setBranchViewData setIdentity track validateCode trackCommerceEvent logEvent disableTracking".split(" "), 0);
// init Branch
branch.init('key_live_YOUR_KEY_GOES_HERE');
</script>
</head>
<body>
</body>
</html>
Then, on your React.js app, add the branch listener directly:
function onResume() {
let branch = window.branch;
// Whatever else you want to do when you receive your branch information.
}
Just define what you want to do with your branch from there onwards.
Basically the heading. I have a strapi app at localhost:1337 which I will fetch in React. I'm not very sure how localhost works, and therefore I want to know if the path will still be relevant when I deploy the react app.
When you deploy your react.js app on any server your url named http://localhost:1337/Dashboard
will be changed. In it http://localhost:1337/ is the base url or domain name. Which will change the server to the new one.
your code will maintain same value for that API and you will have to re-build your code each time you change your API, (most of people use low cost hosting provider which allow only port 80 to be used) my advice is to move your endpoit (backend url) outside your code in a json, .env file ... but what will work on most of platform is a variable defined in your public/index.html (not a best pratice but it will work) ex:
<html>
<head>
<!-- you will add this tag here it will contain your backend url -->
<script>
var bakendUrl = "http://....";
</script>
<!-- some other code here -->
</head>
<body>
<div id="root"></div>
</body>
</html>
I have Google Analytics code set up in my gatsby application.
<script>
var gaId = "UA-xxxxxxxx-1";
var JSLink = "https://www.googletagmanager.com/gtag/js?id=" + gaId;
var JSElement = document.createElement('script');
JSElement.src = JSLink;
document.getElementsByTagName('head')[0].appendChild(JSElement);
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)}
gtag('js', new Date());
gtag('config', gaId);
</script>
When I checked the site with Google Tag Assistant, it says there are multiple installations of the tracking code.
How can I get rid of duplication installations of Global site tag? What recommendation for set up Google Analytics in React app?
Connect all your properties (Analytics, Google Ads) through google tag manager and include tag manager code to your site. It will be solve the problem.
I have a react website and in my html template I put the google analytics tracking code snippet.
The tracking works on my local (so I can actually see my dev session in GA console) but it doesn't work after I deploy to cloud. Here how my template looks like and react just render the root div.
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
<div id="root" />
</body>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="GA link..."></script>
<script>
GA tracking code...
</script>
</html>
My site is here. You can see from the source code the tracking code is there. However current session just doesn't show up in GA.
When I go to your site I see calls going out to Google Tag Manager and Google Analytics and Doubleclick.
Maybe you have a script blocker (uBlock Origin, Noscript, ...) disabled on localhost but active on the production site?
I resolved it eventually. Regenerate another project in GA and use the new project worked for me. Maybe it was something mess up with my old project setup.
I created an angular single-page web app for my customer.
Now they need to integrate the app into a page of their (wordpress) website.
EDIT: in other words they want the app inside an existing wordpress page
what's the best approach?
I tried iframe but it does not work: no resize on app content change and problems with modals.
Thanks
If you need to insert it in an existing page with an already done template you can create a shortcode and a plugin:
create a folder like "your_spa" in the plugin folder of wordpress (/wp-content/plugins/)
create a php file named your_spa.php inside the new generated folder
put this inside the file "your_spa.php"
<?php
/*
Plugin Name: your spa plugin
Description: description
*/
function your_spa_code(){ ?>
<!-- put here your code (this will be inside the body of the page) -->
<?php }
add_shortcode( 'yourspa', 'your_spa_code' );
?>
take care of the links/resources urls (js, json, css): place them anywhere you want them, but remember the path (like in html path => url)
remember to let the apache user read the files (file permissions)
activate the plugin "your spa plugin" inside the wordpress dashboard
use [yourspa] inside a blogpost/page as a shortcut
And now you have created a plugin and a shortcode!
PS: remember that your code will be surrounded by the code of the existing page
It's a little dirty but it's the easies solution.
I had some success with simply rendering Angular's bootstrap code, the <app-root> and <script> tags, just as they are served from a standalone an Angular deployment.
I just added the following HTML in a post, using the HTML editor.
Of course, I had to fiddle the JS script source URLs. Rendering all this HTML could be done with a Wordpress shortcode and plugin that asks for a URL path to the JS files.
<app-root></app-root>
<script type="text/javascript" src="http://localhost:4200/inline.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/polyfills.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/styles.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/scripts.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/vendor.bundle.js"></script>
<script type="text/javascript" src="http://localhost:4200/main.bundle.js"></script>
This worked poorly with the Divi theme and a 'code' module, totally screwed up the page. Attempts to use the offical Wordpress mechanism for including JS scripts (wp_enqueue_script) failed since the <app-root> tag can't be found when the scripts load.