Hi there i'm using ReactGA4 for track my Analytics in Next app. I am facing the issue that i cant see the path where the user is until they reload the page. This is my code.
ReactGA.initialize("UA-xxxxxxx");
ReactGA.send("pageview");
Subscribe to the Router
events
and use the GA pageview
interface.
Remember to use the routeChangeComplete
which will send the pageview via the ReactGA method
Modified nextjs example
import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function MyApp({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url, { shallow }) => {
// REACTGA
// Send pageview with a custom path
ReactGA.send({ hitType: "pageview", page: "/my-path" });
console.log(
`App is changing to ${url} ${
shallow ? 'with' : 'without'
} shallow routing`
)
}
router.events.on('routeChangeComplete', handleRouteChange)
// If the component is unmounted, unsubscribe
// from the event with the `off` method:
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [])
return <Component {...pageProps} />
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.