This article was written 2 years ago. Information and code examples may be out of date.
Hướng dẫn này chỉ cho bạn cách theo dõi lưu lượng truy cập trên ứng dụng React (hoặc trang web) của bạn bằng Google Analytics.
Đầu tiên, hãy cài đặt các gói cần thiết:
Bắt buộc
Để làm theo hướng dẫn này, bạn nên có những điều sau đây:
Gói react-ga là một thư viện mã nguồn mở được thiết kế để hoạt động với phiên bản mới nhất của Google Analytics, Universal Analytics.
Thêm gói vào dự án của bạn.
Với YARN
yarn add react-ga
Với PNPM
pnpm add react-ga
Với NPM
npm i react-ga
Tạo một tệp có tên Analytics.js
bên trong thư mục dự án của bạn.
import ReactGA from 'react-ga';
const Analytics = () => {
// replace this with your google analytics id
const GA_ID = 'UA-000000-01';
ReactGA.initialize(GA_ID);
ReactGA.pageview(window.location.pathname + window.location.search);
};
export default Analytics;
Với React
Chèn đoạn sau vào component mà bạn muốn hiển thị:
import Analytics from './Analytics';
const MyComponent = () => {
Analytics();
// other code here
};
export default MyComponent;
Với Next.js
Chèn đoạn sau vào tệp _document.js
của bạn:
import Document, { Head, HTML, Main, NextScript } from 'next/document';
import Analytics from './Analytics';
class MyDocument extends Document {
render() {
Analytics();
return (
<HTML>
<Head />
<body>
<Main />
<NextScript />
</body>
</HTML>
);
}
}
export default MyDocument;
Cách tốt hơn là triển khai với hook useEffect:
Với React
import React, { useEffect } from 'react';
import Analytics from './Analytics';
const MyPage = () => {
useEffect(() => {
Analytics();
}, []);
// other code
};
export default MyPage;
Với Next.js
import Document, { Head, HTML, Main, NextScript } from 'next/document';
import React, { useEffect } from 'react';
import Analytics from './Analytics';
class MyDocument extends Document {
render() {
useEffect(() => {
Analytics();
}, []);
return (
<HTML>
<Head />
<body>
<Main />
<NextScript />
</body>
</HTML>
);
}
}
export default MyDocument;
Bây giờ hãy kiểm tra công việc của bạn (lưu ý rằng nó sẽ hoạt động ngay cả trên môi trường localhost).