Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending React Router Page Views to Firebase Analytics

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

like image 206
Tzach Avatar asked Apr 09 '20 11:04

Tzach


People also ask

How do I track page views in react?

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.

How to add Firebase Analytics to your react app?

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.

Can I use React-router with Firebase Hosting?

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.

What can you measure with Firebase Analytics?

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.

How do I collect data from Firebase?

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.


Video Answer


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;
}
like image 100
Tzach Avatar answered Oct 18 '22 02:10

Tzach


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

const analytics = firebase.analytics;
like image 1
Visible_Break Avatar answered Oct 18 '22 03:10

Visible_Break