Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To send React Router Page Views to Firebase Analytics, you can use the useEffect hook in your main app component to track page views whenever the location changes. Here's an example:

  1. Import the necessary dependencies:
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import firebase from 'firebase/app';
import 'firebase/analytics';
  1. Initialize Firebase Analytics in your app (outside of the main app component):
firebase.initializeApp({
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  appId: "YOUR_APP_ID",
  measurementId: "YOUR_MEASUREMENT_ID"
});

const analytics = firebase.analytics();
  1. Create a custom hook to track page views:
const usePageView = () => {
  const location = useLocation();

  useEffect(() => {
    analytics.setCurrentScreen(location.pathname);
    analytics.logEvent('page_view');
  }, [location]);
}
  1. Use the usePageView hook in your main app component:
function App() {
  usePageView();

  ...

  return (
    ...
  );
}

This will track every React Router page view as a separate event in Firebase Analytics with the "page_view" event name. You can then view these page views under the "Events" section of your Firebase Analytics dashboard.