How to call document.createElement in Custom Javascript?

I’m trying to integrate the latest Google Analytics and am stuck on something that seems like it should be simple. Calling the following line:

var script = document.createElement('script');

Gives me this error:

TypeError: Cannot read properties of null (reading 'createElement')

How can I create an element so I can put a tracking code on each page?

From some more research I understand now that ‘document’ is not available at all since it’s a React Native app. Is there some kind of equivalent I can use to add an analytics tracking tag to the header of all pages?

One workaround for this is to use a library called react-native-webview, which allows you to embed web content in your React Native app. You can create a new WebView component in your React Native app and use the source prop to load a local HTML file that contains your Google Analytics tracking code.

Here is an example of how you could use the react-native-webview library to add Google Analytics tracking to your React Native app:

import { WebView } from 'react-native-webview';

function GoogleAnalytics() {
  return (
    <WebView
      source={require('./google-analytics.html')}
    />
  );
}

In the above example, the google-analytics.html file should contain the Google Analytics tracking code.

You can also use the injectJavaScript prop which allows you to run JavaScript code on the WebView.

<WebView
  source={require('./google-analytics.html')}
  injectedJavaScript={`
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'GA_MEASUREMENT_ID', 'auto');
    ga('send', 'pageview');
  `}
/>

Note: Make sure you replace ‘GA_MEASUREMENT_ID’ with your actual measurement ID and also the WebView component needs to be imported and wrapped around the component you want to track.

Keep in mind that since React Native uses a JavaScript bridge to communicate with native modules, performance may be impacted when using the react-native-webview library.

(Courtesy of chatGPT :wink:)