React

React integration guide

Adding PureStats to your React application is straightforward. Here's how to set it up for different React setups.

Create React App

For Create React App projects, add the tracking code to your public/index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>My React App</title>

    <!-- PureStats Analytics -->
    <script defer data-domain="yourdomain.com" src="https://purestats.io/pf.min.js"></script>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>
</html>

Vite

For Vite projects, add the script to your index.html in the project root:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Vite App</title>

    <!-- PureStats Analytics -->
    <script defer data-domain="yourdomain.com" src="https://purestats.io/pf.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
</body>
</html>

Tracking Custom Events

Create a utility hook for tracking events:

// hooks/useAnalytics.js
export function useAnalytics() {
  const trackEvent = (eventName, props = {}) => {
    if (typeof window !== 'undefined' && window.purestats) {
      window.purestats(eventName, { props })
    }
  }

  return { trackEvent }
}

// Usage in a component
import { useAnalytics } from '../hooks/useAnalytics'

function SignupForm() {
  const { trackEvent } = useAnalytics()

  const handleSubmit = (e) => {
    e.preventDefault()
    trackEvent('Signup', { plan: 'free' })
    // Your form logic
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
      <button type="submit">Sign Up</button>
    </form>
  )
}

React Router Integration

PureStats automatically tracks page changes when using React Router. No additional setup is required.

How it works: PureStats listens for pushState and popstate events, which React Router uses for navigation. This means all route changes are automatically tracked.

TypeScript

Add type declarations for TypeScript projects:

// src/types/global.d.ts
declare global {
  interface Window {
    purestats: (event: string, options?: { props?: Record<string, any> }) => void
  }
}

export {}