| 1 | import { usePostHog } from "posthog-js/react"; |
| 2 | import { useEffect } from "react"; |
| 3 | import { useLocation, useSearchParams } from "react-router-dom"; |
| 4 | |
| 5 | /** |
| 6 | * This is copied from here: https://posthog.com/tutorials/single-page-app-pageviews#tracking-pageviews-in-nextjs-app-router |
| 7 | * They don't have a non-NextJS doc for React apps. |
| 8 | */ |
| 9 | export default function PostHogPageView() { |
| 10 | const { pathname } = useLocation(); |
| 11 | const [searchParams] = useSearchParams(); |
| 12 | const posthog = usePostHog(); |
| 13 | |
| 14 | // Track pageviews |
| 15 | useEffect(() => { |
| 16 | if (pathname && posthog) { |
| 17 | let url = window.origin + pathname; |
| 18 | |
| 19 | if (searchParams.toString()) { |
| 20 | url = url + `?${searchParams.toString()}`; |
| 21 | } |
| 22 | |
| 23 | posthog.capture("$pageview", { |
| 24 | $current_url: url, |
| 25 | pathname, |
| 26 | }); |
| 27 | } |
| 28 | }, [pathname, searchParams, posthog]); |
| 29 | |
| 30 | return null; |
| 31 | } |