TECH

SPA(Single Page Application) GA4 적용

AKA.DM 2023. 9. 15. 07:23
반응형

1. GA4 생성
2. 추적ID복사
3. React-ga 라이브러리 설치
https://github.com/react-ga/react-ga

 

GitHub - react-ga/react-ga: React Google Analytics Module

React Google Analytics Module. Contribute to react-ga/react-ga development by creating an account on GitHub.

github.com

4. GoogleAnalyticsSetting.tsx 파일 생성

import { useEffect, useState } from 'react';
import ReactGA from 'react-ga';
import { useLocation } from 'react-router-dom';

const GoogleAnalyticsSetting = () => {
	const location = useLocation();
	const [init, setInit] = useState<boolean>(false);

	const gaTrackingId = 'US-1234512345-2';
	useEffect(() => {
		if (!window.location.href.includes('localhost')) {
			ReactGA.initialize(gaTrackingId, { debug: true });
		}
		setInit(true);
	}, []);

	useEffect(() => {
		if (init) {
			ReactGA.pageview(location.pathname + location.search);
		}
	}, [init, location]);
};

export default GoogleAnalyticsSetting;



5. App.tsx에 해당함수 import

import { Stack } from '@mui/material';
import { useRoutes } from 'react-router-dom';
import { allRoutes } from '../pages/routes';
import GoogleAnalyticsSetting from './GoogleAnalyticsSetting';

export function App() {
	GoogleAnalyticsSetting();

	// @ts-ignore
	const routes = useRoutes(allRoutes);
	return (
		<Stack
			flex={1}
			sx={{ overflowY: 'auto' }}>
			{routes}
		</Stack>
	);
}

export default App;

 

반응형