My app uses React Router's BrowserRouter
. How can I track page views and send them to google firebase analytics (I've already installed firebase-analytics.js
).
Pass trackPageViews into the listen method on the history object to make sure every page view is tracked. Call the trackPageViews function inside of useEffect, and pass the history object to its dependency array specifying that useEffect should be called every time history is updated.
To add Firebase Analytics to our React app, we will use ga-4-react package. This package can be used to include Google Analytics tracking code in a website or app that uses React for its front-end codebase. This goes without saying but of course, we’ll need a react app to get started.
I have a react app that uses react-router with a Router that looks like: The app is hosted using Firebase hosting. If I open my website and click around such that the router takes me to /map/uid, it loads fine.
Measure performance, and so much more, of your React App with Firebase Analytics. Data is everywhere. Being able to see how your website, or app, is doing in real-time is a blessing.
Just add the Firebase SDK to your new or existing app, and data collection begins automatically. You can view analytics data in the Firebase console within hours. Log custom data. You can use Analytics to log custom events that make sense for your app, like E-Commerce purchases or achievements.
Just render the following component anywhere inside your <BrowserRouter>
:
import { useLocation } from "react-router-dom";
import { useEffect } from "react";
function FirebaseAnalytics() {
let location = useLocation();
useEffect(() => {
const analytics = window.firebase && window.firebase.analytics;
if (typeof analytics === "function") {
const page_path = location.pathname + location.search;
analytics().setCurrentScreen(page_path);
analytics().logEvent("page_view", { page_path });
}
}, [location]);
return null;
}
As an alternative / additional consideration to Tzach's answer, you may prefer to import firebase and set
const analytics = firebase.analytics;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With