Back to Installation

React Installation Guide

Step-by-step guide to install TwoBucks Analytics on React.

Quick Start

Add the TwoBucks script to your main HTML file or React app entry point:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script
      src="https://twobucks.ai/script.js"
      data-website-id="your-website-id"
      async
    ></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

React Router Setup

For Single Page Applications (SPAs), TwoBucks automatically tracks route changes. However, you may need to manually trigger pageviews for certain routers:

React Router v6

// App.jsx
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'

function App() {
  const location = useLocation()

  useEffect(() => {
    // TwoBucks automatically tracks route changes via History API
    // No manual tracking needed
  }, [location])

  return (
    // Your app content
  )
}

React Router v5

// App.jsx
import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

function App() {
  const history = useHistory()

  useEffect(() => {
    // TwoBucks automatically tracks route changes
    const unlisten = history.listen(() => {
      // Route change is automatically tracked
    })
    return unlisten
  }, [history])

  return (
    // Your app content
  )
}

Programmatic Tracking

Track custom events in your React components:

// components/Button.jsx
import { useEffect } from 'react'

function Button({ onClick, children }) {
  const handleClick = () => {
    // Track button click
    if (window.twobucks) {
      window.twobucks('button_click', {
        button_text: children,
        page: window.location.pathname
      })
    }
    onClick?.()
  }

  return <button onClick={handleClick}>{children}</button>
}

Custom Hook

Create a reusable hook for tracking:

// hooks/useTracking.js
import { useEffect } from 'react'

export function useTracking(eventName, properties) {
  useEffect(() => {
    if (window.twobucks && eventName) {
      window.twobucks(eventName, properties)
    }
  }, [eventName, properties])
}

// Usage
function ProductPage({ productId }) {
  useTracking('product_view', { product_id: productId })
  return <div>Product Page</div>
}

Common Issues

Script Not Loading

  1. Ensure script is in <head> or before </body>
  2. Check browser console for errors
  3. Verify data-website-id is correct

Route Changes Not Tracked

TwoBucks automatically tracks History API changes. If routes aren't tracked:

  1. Ensure you're using React Router (not window.location)
  2. Check that script loads before navigation occurs

TypeScript Support

Add type definitions:

// types/twobucks.d.ts
interface Window {
  twobucks: (eventName: string, properties?: Record<string, string>) => void
  twobucks?: {
    identify: (userId: string, properties?: Record<string, string>) => void
    checkConsent: () => boolean
  }
}

Next Steps