Sending React Router Page Views to Firebase Analytics
Asked Answered
M

3

8

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

Metathesis answered 9/4, 2020 at 11:59 Comment(0)
M
11

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;
}
Metathesis answered 9/4, 2020 at 11:59 Comment(1)
setCurrentScreen is deprecated. It's better to use only the logEvent method. firebase.google.com/docs/reference/js/v8/…Chestnut
I
1

As an alternative / additional consideration to Tzach's answer, you may prefer to import firebase and set

const analytics = firebase.analytics;
Inanna answered 23/2, 2021 at 16:18 Comment(0)
B
1

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;
}
Beefsteak answered 2/4, 2023 at 11:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.