Trackthemetric + React Router
Here's how you can set up Trackthemetric analytics in a React Router application.
Option 1Inject the script in your root component
The easiest way to make sure the tracking code runs on every route is to add it at the very top level of your app.
1. Open your root file: App.jsx
or main.jsx
file.
2. Use a useEffect
hook to insert the TrackTheMetric script into the <head>
.
Here is an example setup (App.jsx
) :
import { useEffect } from "react"; function App() { useEffect(() => { // Inject Trackthemetric script const script = document.createElement("script"); script.defer = true; script.setAttribute("id", "TrackTheMetric"); script.setAttribute("data-website-id", "YOUR_WEBSITE_ID"); script.setAttribute("data-domain", "YOUR_DOMAIN.COM"); script.src = "https://app.trackthemetric.com/tracker.js"; document.head.appendChild(script); // Clean up when component unmounts return () => { document.head.removeChild(script); }; }, []); return ( // Your app JSX ); } export default App;
Make sure to replace the YOUR_WEBSITE_ID
and YOUR_DOMAIN.COM
with your actual website ID and domain.
Option 2Add it directly in public/index.html
If you prefer not to handle it in React code, you can drop the snippet straight into your HTML:
<script defer id="TrackTheMetric" data-website-id="YOUR_WEBSITE_ID" data-domain="YOUR_DOMAIN.COM" src="https://app.trackthemetric.com/tracker.js" ></script>
3Verifying the setup
Once you've deployed your project:
- Open your production site in the browser.
- Head over to your Trackthemetric dashboard.
- Within a few minutes, you should see traffic starting to appear.