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
).
Sending React Router Page Views to Firebase Analytics
Asked Answered
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;
}
As an alternative / additional consideration to Tzach's answer, you may prefer to import firebase and set
const analytics = firebase.analytics;
If you are using React + TypeScript some type errors will appear. Also, in my opinion, it is better to use a React Hook because in this case you are adding logic to a component (not another component). I leave my proposal down below:
import { useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import { getAnalytics, logEvent } from '@firebase/analytics';
export function useFirebaseRoutesAnalytics() {
const location = useLocation();
useEffect(() => {
const analytics = getAnalytics();
logEvent(analytics, 'screen_view', {
firebase_screen: location.pathname, // <- In my case I do not want to include search params, so 'location.pathname' is just what I want
firebase_screen_class: 'firebase-routes-analytics', // <- This name is up to you
});
}, [location]);
return null;
}
© 2022 - 2025 — McMap. All rights reserved.
setCurrentScreen
is deprecated. It's better to use only the logEvent method. firebase.google.com/docs/reference/js/v8/… – Chestnut