본문 바로가기
프론트앤드 개발

react로 GA(google Analytics) mobile tracker 만들기

by 긴자손 2024. 1. 30.
728x90
반응형
import { useEffect, useRef, useState } from "react";
import { useTracker } from "./util/Tracker";

export const Mobile = () => {
  const tracker = useTracker();
  const [foldState, setFoldState] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const [isTracked, setIsTracked] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          // 요소가 뷰포트에 들어오는 경우에만 트래킹
          if (entry.isIntersecting && !isTracked) {
            tracker.trackingScroll({
              depth1: "GA",
              depth2: "첫번재",
            });
            setIsTracked(true); // 요소가 한 번 트래킹되면 다시 트래킹되지 않도록 상태를 변경
          }
        });
      },
      {
        rootMargin: "0px", // 필요에 따라 rootMargin을 조정할 수 있습니다.
        threshold: 0.1, // 요소가 10% 보일 때 콜백이 실행되도록 threshold 조정
      }
    );

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      observer.disconnect();
    };
  }, [isTracked, tracker]); // 의존성 배열에 isTracked와 tracker를 추가
  return (
    <div
      ref={ref}
      }}
    >
    </div>
  );
};
728x90
반응형