Add tracker to React Router App
1. Include the UXWizz tracking snippet in your index.html file
You should now be able to use UST
in your application. If you use TypeScript, you can declare UST
as any. TypeScript typings for the tracker will be released soon.
2. Track pageviews
By default, being a SPA, only the entry pageview will be tracked.
To track all consequent pageviews, include a new UXWizzPageview.ts in your app
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export default function UXWizzPageview() {
const location = useLocation();
const isInitialLoad = useRef(true);
useEffect(() => {
if (isInitialLoad.current) {
isInitialLoad.current = false
return;
};
if (typeof window === 'undefined') return;
const ust = (window as typeof window & { UST: { trackNewPage: () => void } })['UST'];
if (!ust || !ust.trackNewPage) return;
ust.trackNewPage(); // Call on route change, but not on initial load
}, [location]);
return null;
};
Then, in your main App component, include UXWizzPageview
.
// ...
import UXWizzPageview from './UXWizzPageview';
export default function App() {
return (
<Router>
<UXWizzPageview/>
{/* your other components */}
</Router>
);
}
If you don't use TypeScript, you can simply remove the typings replace this line:
const ust = (window as typeof window & { UST: { trackNewPage: () => void } })['UST'];
with
const ust = window['UST'];
Last updated
Was this helpful?