All Articles

Google Analytics(GA) 생성하기

React 프로젝트에 Google Analytics 연동하는 방법

  1. index.html 파일에 수동으로 Google 태그 설치
  • 관리 → 데이터스트림 메뉴에서 확인 가능 image.png
<!-- 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>
  1. react-ga, history 설치
  1. App.tsx에서 추적하기
  • 측정 ID를 환경변수로 저장하기
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;
}

Published Jul 8, 2023

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