React (Single Page App)

Integration for React apps with react-router or similar routing libraries.

Step 1: Add the script

Add the script to your index.html:

public/index.html

<!DOCTYPE html>
<html lang="sv">
<head>
  <meta charset="UTF-8" />
  <title>Min React-app</title>

  <!-- Besökskollen tracking -->
  <script defer
    data-site-id="DIN-SAJT-ID"
    data-api="https://besokskollen.se"
    src="https://besokskollen.se/script.js">
  </script>
</head>
<body>
  <div id="root"></div>
</body>
</html>

SPA Navigation

Our script automatically handles client-side navigation. It listens to history.pushState and popstate events.

This works automatically with:

  • React Router (v5 and v6)
  • Reach Router
  • TanStack Router
  • Wouter

Track events

Create a hook to easily track events in your components:

hooks/useAnalytics.ts

declare global {
  interface Window {
    va?: (type: string, name: string, props?: object) => void;
  }
}

export function useAnalytics() {
  const trackEvent = (name: string, props?: object) => {
    if (typeof window !== 'undefined' && window.va) {
      window.va('event', name, props);
    }
  };

  return { trackEvent };
}

Use the hook in your components:

import { useAnalytics } from './hooks/useAnalytics';

function ProductCard({ product }) {
  const { trackEvent } = useAnalytics();

  const handleAddToCart = () => {
    trackEvent('Add to Cart', {
      productId: product.id,
      price: product.price
    });
    // ... lägg till i kundvagn
  };

  return (
    <div>
      <h3>{product.name}</h3>
      <button onClick={handleAddToCart}>
        Lägg i kundvagn
      </button>
    </div>
  );
}

Vite

If you're using Vite, add the script to index.html in the project root.

Create React App

Add the script to public/index.html.