# React Router

## Add Humblytics Analytics to a React Router Site

### 1 · Sign up (or log in)

Visit humblytics.com → Start Free Trial. Finish signup—or log in to your existing workspace.

### 2 · Add your website in Humblytics

In the sidebar, click **Add Website**.

* **Domain** – enter `your-domain.com` (omit `https://` and `www`)
* **Site Name** – internal label (e.g. `Marketing-React`)

Copy the snippet from **Install Tracking Code**:

html

```html
<!-- Start Humblytics Tracking Code -->
<script async src="https://app.humblytics.com/hmbl.min.js?id=YOUR_ID_HERE"></script>
<!-- End Humblytics Tracking Code -->
```

Keep this tab open—we'll return and click **Verify Website** once the tag is live.

### 3 · Add the script to your React Router app

⚠️ **Important for SPAs**: React Router doesn't reload the page on navigation, so you need to manually track route changes (see Option B).

#### Option A: Simple setup (tracks initial page load only)

**Best for:** Quick setup, or if you'll handle route tracking separately

**For Create React App:**

1. Open `public/index.html`
2. Add your Humblytics script just before `</head>`:

html

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>React App</title>
  
  <!-- Humblytics Analytics -->
  <script async src="https://app.humblytics.com/hmbl.min.js?id=YOUR_ID_HERE"></script>
</head>
<body>
  <div id="root"></div>
</body>
</html>
```

**For Vite:**

1. Open `index.html` (in root directory, not `/public`)
2. Add the same script before `</head>`

**Limitation**: This only tracks the initial page load. Route changes won't be tracked automatically.

#### Option B: Full SPA tracking (recommended)

**Best for:** Tracking all route changes in your React Router app

**React Router v6 setup:**

Create a tracking component that listens to route changes:

jsx

```jsx
// src/components/Analytics.jsx
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

export function Analytics() {
  const location = useLocation();

  useEffect(() => {
    // Load Humblytics script on mount
    const script = document.createElement('script');
    script.src = 'https://app.humblytics.com/hmbl.min.js?id=YOUR_ID_HERE';
    script.async = true;
    document.head.appendChild(script);

    return () => {
      // Cleanup on unmount
      document.head.removeChild(script);
    };
  }, []); // Empty array = run once on mount

  useEffect(() => {
    // Track route changes
    if (window.hmbl) {
      window.hmbl.trackPageview();
    }
  }, [location.pathname]); // Run on every route change

  return null; // This component doesn't render anything
}
```

Then add it to your app root:

jsx

```jsx
// src/App.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { Analytics } from './components/Analytics';

function App() {
  return (
    <BrowserRouter>
      <Analytics />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        {/* your other routes */}
      </Routes>
    </BrowserRouter>
  );
}

export default App;
```

#### Option C: Production-only tracking

**Best for:** Disabling analytics in development

jsx

```jsx
// src/components/Analytics.jsx
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

export function Analytics() {
  const location = useLocation();

  useEffect(() => {
    // Only load in production
    if (process.env.NODE_ENV !== 'production') return;

    const script = document.createElement('script');
    script.src = 'https://app.humblytics.com/hmbl.min.js?id=YOUR_ID_HERE';
    script.async = true;
    document.head.appendChild(script);

    return () => {
      if (document.head.contains(script)) {
        document.head.removeChild(script);
      }
    };
  }, []);

  useEffect(() => {
    if (process.env.NODE_ENV !== 'production') return;
    
    if (window.hmbl) {
      window.hmbl.trackPageview();
    }
  }, [location.pathname]);

  return null;
}
```

**Note**: Replace `YOUR_ID_HERE` with your actual project ID from Humblytics.

### 4 · Verify installation

1. **Build and deploy** your app to production
2. Return to Humblytics and click **Verify Website**
3. Open your live site in a private/incognito window
4. Navigate between routes to test route change tracking
5. Within \~30 seconds you should see a green **Verified** badge and live visitor count

**If verification fails, check:**

**React Router-specific issues:**

* You deployed to production (not testing on localhost)
* If using Option B, verify `Analytics` component is mounted in your app
* Check browser console for errors (F12 → Console)
* Route changes should trigger `hmbl.trackPageview()` (check Network tab in DevTools)
* Script loads before route changes happen (use Option B for best results)

**General issues:**

* Script ID matches your project in Humblytics
* Open Developer Tools (F12) → **Network** tab, refresh page, and search for `hmbl.min.js`
* View page source (right-click → View Page Source) and search for "humblytics"
* No ad-blockers or browser extensions are blocking the script

**Debug route tracking:** Add console logs to verify tracking:

jsx

```jsx
useEffect(() => {
  console.log('Route changed:', location.pathname);
  if (window.hmbl) {
    console.log('Tracking pageview');
    window.hmbl.trackPageview();
  } else {
    console.log('Humblytics not loaded yet');
  }
}, [location.pathname]);
```

### 5 · Explore & optimize

* **Dashboard** – track traffic, top pages, and referrers (including all route changes)
* **Heatmaps** – auto-generated scroll and click tracking across all routes
* **Experiments** – run A/B tests powered directly by Humblytics


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.humblytics.com/how-to-get-started/react-router.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
