score:5

Accepted answer

You might want to create a Layout Component

Example:

// components/layout.js
import React from 'react'
import { initGA, logPageView } from '../utils/analytics'

export default class Layout extends React.Component {
  componentDidMount () {
    if (!window.GA_INITIALIZED) {
      initGA()
      window.GA_INITIALIZED = true
    }
    logPageView()
  }
  render () {
    return (
      <div>
        {this.props.children}
      </div>
    )
  }
}

You can then use Layout to wrap other components

Example:

// pages/about.js
import Layout from '../components/layout'

export default () => (
  <Layout>
    <div>About us</div>
  </Layout>
)

Example:

// utils/analytics.js
import ReactGA from 'react-ga'

export const initGA = () => {
  console.log('GA init')
  ReactGA.initialize('UA-xxxxxxxxx-1')
}
export const logPageView = () => {
  console.log(`Logging pageview for ${window.location.pathname}`)
  ReactGA.set({ page: window.location.pathname })
  ReactGA.pageview(window.location.pathname)
}
export const logEvent = (category = '', action = '') => {
  if (category && action) {
    ReactGA.event({ category, action })
  }
}
export const logException = (description = '', fatal = false) => {
  if (description) {
    ReactGA.exception({ description, fatal })
  }
}

I hope this helps.

score:6

hey it seems like you find the answer but here is my take on it, maybe it will help someone else.

componentDidMount can only work in class component. from the image it's shown that About is functional component.

in this cases, React.useEffect is the equivalent of componentDidMount in functionl components. It can be used to invoke the init (or do any other side effects)

 const About = () => {
    
    React.useEffect(() => {
    
     ReactGA.init()
    
    }, [])
    
    //rest of the component
return ( 

<section> .... </section>

)

    
}

A little note you might want to consider, is using the _app.js component.

this is the next js base component and it wraps all of the pages, so any logic or layout used in all pages can be inserted there.

function MyApp({ Component, pageProps }) {
  React.useEffect(() => {
    ReactGA.init()
  }, [])
  return (
    <div>
      <Header />
      <Component {...pageProps} />
      <Footer />
    </div>
  )
}

this will run only on the component mount, and the benefit is that the app won't load it anymore on any other component mount and the api will be accessible through out the app.


Related Query

More Query from same tag