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
).
Just render the following component anywhere inside your <BrowserRouter>
:
import { useLocation } from "react-router-dom";
import { useEffect } from "react";
function FirebaseAnalytics() {
const 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;
}