Google Analytics

react-ga4

Posted by ETHAN KIM on January 10, 2023 · 4 mins read
React JavaScript

기본 프로세스

  • 일반 MPA 웹사이트 단순연결
    1. 초기 진입 파일에 script 코드 실행
  • 리액트 SPA의 경우
    1. 페이지 렌더링 시 감지할 수 있어야함
    2. react-ga라이브러리(유니버셜코드지원 UA)
    3. react-ga4 라이브러리 사용하여 연동 (GA코드 사용)


일반 스크립트 방식 (MPA)


./public/index.html

  • 빌드 전 후 상관없이 초기 진입 html파일 script 이식
  • page변경 감지 불가능 react router 진입 페이지만 인식 가능
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />  
    <script src="https://js.tosspayments.com/v1"></script><!--PG TOSSPAYMENTS--> 
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-577DV87WTC"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-577DV87WTC');
    </script>    
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>


리액트 라이브러리 이용 (SPA)


./src/index.js

  • 진입점에서 발급받은 GA코드를 넣어 라이브러리 함수 초기화
import ReactGA from "react-ga4";

//google analytics connect
ReactGA.initialize(process.env.REACT_APP_GOOGLE_ANALYTICS);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <App />
);


./route/Description.js

  • page로드 시 파라미터값을 정보로 전달하는 것도 가능
//------------------------------ MODULE -------------------------------------
import ...
import ReactGA4 from 'react-ga4';

//------------------------------ CSS ----------------------------------------
style ...

//------------------------------ COMPONENT ----------------------------------
const Description = React.memo(({id, closeEvent}) => {
    logic ...
    
    useEffect(() => { 
        //google analytics send
        const thisId = nowId ? nowId : state.id;
        ReactGA4.send({hitType: "pageview", path: `/Description/${thisId}`, location: `/Description/${thisId}`, title: `/Description/${thisId}`});

        ...
    }, []);

    //render
    return (
        <SimpleMotion>
        <StyledDescription>
            {shareGear}
            <StyledHeader id="webDescHeader">
                <StyledBack size='2em' onClick={moveBack}/>
            </StyledHeader>
            <StyledContainer>
                {loading? <StyledBannerLoading /> : bannerGear}
                {infoGear}
                {myTeamGear}
                {partyGear}
                {reviewGear}
                {sellerGear}
                {detailGear}
                {linkGear}
                {buyGear}
            </StyledContainer>
            {modalGear}
            {optionWindowGear}
            {loginAlertGear}
            {alertGear}
            {htmlGear}
        </StyledDescription>
        </SimpleMotion>
    );
});

export default Description;
});

export default Navigation;