Adding analytics to React apps

Panelbear is often used with React-based single-page apps. First, you'll need to add your site to Panelbear. You'll get a tracking snippet for your web app.

The tracking snippet is a small piece of code that runs on your website, and it collects the anonymous metrics which powers your dashboards.

There's two ways to integrate this snippet with your React app - let's take a look.

Method 1: Add the script to your HTML document header

Just add the script shown in your Site Settings to your website's HTML <head> section.

You can enable the option spaMode: 'history' to automatically track navigation changes on the client.

For example (don't forget to set your Site ID in both locations):

<!-- Panelbear Analytics - We respect your privacy -->
<script async src="https://cdn.panelbear.com/analytics.js?site=YOUR_SITE_ID"></script>
<script>
    window.panelbear = window.panelbear || function() { (window.panelbear.q = window.panelbear.q || []).push(arguments); };
    panelbear('config', {
        site: 'YOUR_SITE_ID',
        spaMode: 'history',
        debug: false,
    });
</script>

Method 2: Add the script via npm or yarn

Simply install the library in your project:

npm install @panelbear/panelbear-js

# Or with yarn:
yarn add @panelbear/panelbear-js

You can now import, and use the Panelbear client on your project.

import * as Panelbear from "@panelbear/panelbear-js";

// Load the Panelbear tracker once in your app
Panelbear.load("YOUR_SITE_ID");

// This is how you record page views
// You should trigger this on router/page changes
Panelbear.trackPageview();

// You can also trigger custom events
Panelbear.track("NewsletterSignup");

Check your installation

After you have added our analytics script to the HTML of your website, you should be able to see pageviews show up in the dashboard within a minute of the visitors coming into your website.

If you need help, you can reach out to us at support@panelbear.com.

Tip: Check out our local development guide for some tips and tricks when testing Panelbear on your machine.