Sending React Router Page Views to Firebase Analytics

Viewed 1693

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).

2 Answers

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;
Related