Skip to content

Commit

Permalink
[add] Gtagの設定
Browse files Browse the repository at this point in the history
  • Loading branch information
K-Kizuku committed Jul 14, 2023
1 parent 409d12a commit 38595ac
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
NEXT_PUBLIC_BACKEND_API=
NEXT_PUBLIC_BACKEND_API=
NEXT_PUBLIC_GA_ID=
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
39 changes: 39 additions & 0 deletions src/components/Common/others/Gtag.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
/>
<Script
id="gtag-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}');
`,
}}
/>
</>
);
};

0 comments on commit 38595ac

Please sign in to comment.