Google Analytics(GA) 생성하기

1 min read
React 프로젝트에 Google Analytics 연동하는 방법
- index.html 파일에 수동으로 Google 태그 설치
관리 → 데이터스트림 메뉴에서 확인 가능
<!-- Google tag (gtag.js) -->
<script async src="<https://www.googletagmanager.com/gtag/js?id=G-000000000>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-000000000');
</script>
- react-ga, history 설치
- App.tsx에서 추적하기
REACT_APP_GA_TRACKING_ID = G - 000000000;
- App.tsx파일에 코드 추가
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga4";
/**
* uri 변경 추적 컴포넌트
* uri가 변경될 때마다 pageview 이벤트 전송
*/
const trackingId = process.env.REACT_APP_GA_TRACKING_ID;
export default function RouteChangeTracker() {
const location = useLocation();
useEffect(() => {
if (trackingId) {
ReactGA.initialize(trackingId);
ReactGA.set({ page: location.pathname });
ReactGA.send("pageview");
}
}, [location]);
return null;
}
0
Subscribe to my newsletter
Read articles from Kayoung directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Kayoung
Kayoung
프론트엔드 개발자 김가영입니다. 개발과 일에 대한 생각을 주로 씁니다. https://velog.io/@kykim_dev/posts (2023 이전 블로깅)