Skip to content

Commit

Permalink
#91 feat: 구글 애널리틱스 추적 연결
Browse files Browse the repository at this point in the history
  • Loading branch information
MyungJiwoo committed Oct 4, 2024
1 parent 6f0483b commit 7b87d67
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import Error403Page from './pages/Error403Page';
import { useMediaQuery } from 'react-responsive';
import Flex from './components/Flex';
import { MobileDisplay } from './styles/ErrorPageStyled';
import RouteChangeTracker from './components/RouteChangeTracker';

const queryClient = new QueryClient();

Expand Down Expand Up @@ -260,6 +261,8 @@ const App: React.FC = () => {
style={{ width: '21.875rem', lineHeight: '1.5rem' }}
/>
<RouterProvider router={router(isLoggedIn)} />

{/* <RouteChangeTracker /> */}
</AuthProvider>

<ReactQueryDevtools initialIsOpen={false} />
Expand Down
43 changes: 43 additions & 0 deletions src/components/RouteChangeTracker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import ReactGA from 'react-ga4';

/**
* 구글 애널리틱스 사용하기 위함.
* uri 변경 추적 컴포넌트
* uri가 변경될 때마다 pageview 이벤트 전송
*/
const RouteChangeTracker: React.FC = () => {
const location = useLocation();
const [initialized, setInitialized] = useState(false);

// localhost는 기록하지 않음
// useEffect(() => {
// if (!window.location.href.includes('localhost')) {
// process.env.REACT_APP_GOOGLE_ANALYTICS_TRAKING_ID &&
// ReactGA.initialize(process.env.REACT_APP_GOOGLE_ANALYTICS_TRAKING_ID);
// setInitialized(true);
// }
// }, []);

// location 변경 감지시 pageview 이벤트 전송
useEffect(() => {
if (initialized) {
ReactGA.set({ page: location.pathname });
ReactGA.send('pageview');
}
}, [initialized, location]);

// 개발용
useEffect(() => {
process.env.REACT_APP_GOOGLE_ANALYTICS_TRAKING_ID &&
ReactGA.initialize(process.env.REACT_APP_GOOGLE_ANALYTICS_TRAKING_ID);
ReactGA.set({ page: location.pathname });
ReactGA.send('pageview');
}, [location]);

// JSX에서 사용하기 위해 null 반환
return null;
};

export default RouteChangeTracker;
5 changes: 5 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import GlobalStyle from './styles/GlobalStyle';
import ReactGA from 'react-ga4';

if (process.env.REACT_APP_GOOGLE_ANALYTICS_TRAKING_ID) {
ReactGA.initialize(process.env.REACT_APP_GOOGLE_ANALYTICS_TRAKING_ID);
}

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
Expand Down

0 comments on commit 7b87d67

Please sign in to comment.