-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
google analyics now works with react router dom
- Loading branch information
Showing
4 changed files
with
94 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/** | ||
* Google Analytics tracking hook. | ||
*/ | ||
|
||
import { useEffect } from 'react'; | ||
import { useHistory } from 'react-router-dom'; | ||
|
||
declare global { | ||
interface Window { | ||
gtag?: ( | ||
key: string, | ||
trackingId: string, | ||
config: { page_path: string }, | ||
) => void; | ||
} | ||
} | ||
|
||
export const useTracking = ( | ||
trackingId: string | undefined = 'G-814B22G7SF', | ||
) => { | ||
const { listen } = useHistory(); | ||
|
||
useEffect(() => { | ||
const unlisten = listen(location => { | ||
if (!window.gtag) return; | ||
if (!trackingId) { | ||
console.log( | ||
'Tracking not enabled, as `trackingId` was not given and there is no `GA_MEASUREMENT_ID`.', | ||
); | ||
return; | ||
} | ||
|
||
window.gtag('config', trackingId, { page_path: location.pathname }); | ||
}); | ||
|
||
return unlisten; | ||
}, [trackingId, listen]); | ||
}; |