From 38595ace45cd33cf6f51330be0427fe9f744ba57 Mon Sep 17 00:00:00 2001 From: K-Kizuku Date: Fri, 14 Jul 2023 19:44:55 +0900 Subject: [PATCH] =?UTF-8?q?[add]=20Gtag=E3=81=AE=E8=A8=AD=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.sample | 3 ++- package.json | 1 + src/components/Common/others/Gtag.tsx | 39 +++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/components/Common/others/Gtag.tsx diff --git a/.env.sample b/.env.sample index 82a9799..2dc3a29 100644 --- a/.env.sample +++ b/.env.sample @@ -1 +1,2 @@ -NEXT_PUBLIC_BACKEND_API= \ No newline at end of file +NEXT_PUBLIC_BACKEND_API= +NEXT_PUBLIC_GA_ID= \ No newline at end of file diff --git a/package.json b/package.json index ca500fd..3a3c2ae 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "@storybook/blocks": "^7.0.22", "@storybook/nextjs": "^7.0.22", "@storybook/react": "^7.0.22", + "@types/gtag.js": "^0.0.12", "@types/react-infinite-scroller": "^1.2.3", "@types/react-scroll": "^1.8.7", "@types/uuid": "^9.0.2", diff --git a/src/components/Common/others/Gtag.tsx b/src/components/Common/others/Gtag.tsx new file mode 100644 index 0000000..d69f29f --- /dev/null +++ b/src/components/Common/others/Gtag.tsx @@ -0,0 +1,39 @@ +import Script from "next/script"; +import { useRouter } from "next/router"; +import { useEffect } from "react"; + +export const Gtag = () => { + const router = useRouter(); + useEffect(() => { + const handleRouterChange = (url: any) => { + window.gtag("config", process.env.NEXT_PUBLIC_GA_ID ?? "", { + page_path: url, + }); + }; + router.events.on("routeChangeComplete", handleRouterChange); + return () => { + router.events.off("routeChangeComplete", handleRouterChange); + }; + }, [router.events]); + return ( + <> +