Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactGA.initialize must be called first

I am getting the following warning multiple times (for multiple pages) despite me initializing at the root of my app. This makes me wonder if google analytics is even working properly? [react-ga] ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually

I am using ReactGA to handle my google analytics tags, and I cannot get it to work. According to the documentation and a handful of other questions about this online, all I need to do is insert this at my application root:

App.js:

import ReactGA from 'react-ga';
ReactGA.initialize('G-xxxxxxxxxx');

const app = () => (
    // Root level components here, like routing and navigation
)

I am using Server Side Rendering, so I am making sure the window object exists before tracking. This line is put at the end of my imports on each of my pages:

example page.js:

import ReactGA from 'react-ga';
if (typeof(window) !== 'undefined') {
    ReactGA.pageview(window.location.pathname + window.location.search);
}

function page() {
    return(<div className="page">Hello, World</div>)
}

export default page;

At this point, there isn't a lot of information on how to set up Google Analytics for SSR applications, so I'm not entirely sure what I need to do to get this working. Any help is appreciated!

like image 388
Matt Strom Avatar asked Mar 01 '20 04:03

Matt Strom


People also ask

What does ReactGA initialize do?

ReactGA. initialize(gaTrackingID, options) GA must be initialized using this function before any of the other tracking functions will record any data. The values are checked and sent through to the ga('create', ...

What is ReactGA?

React Google Analytics Module This is a JavaScript module that can be used to include Google Analytics tracking code in a website or app that uses React for its front-end codebase.


1 Answers

I finally found the solution after a lot of tinkering with potential solutions. Since pageview was being fired before initialize could finish, I tired delaying pageview as much as I could by placing it in componentDidMount(). That implementation looks like this:

App.js:

//imports
import ReactGA from 'react-ga';
ReactGA.initialize('UA-xxxxxxxxx-x');

const App = () => (
  <div className="App">
    <Navigation />
            
    <AppRouting />
  </div>
);

Page.js:

import ReactGA from 'react-ga';

class MyPage extends React.Component {
    componentDidMount() {
        ReactGA.pageview(window.location.pathname + window.location.search);
    }

    render() {
        return(
            <Component />
        );
    }
}
like image 200
Matt Strom Avatar answered Sep 22 '22 12:09

Matt Strom