npm package: @rakutenanalytics/rat-react
Description: A comprehensive React SDK for Rakuten Analytics tracking, providing React hooks and components for seamless analytics integration in React applications.
Latest version: 0.3.2

# Rakuten Analytics React SDK

A comprehensive React SDK for Rakuten Analytics tracking, providing React hooks and components for seamless analytics integration in React applications.

## Features

- ✅ **React Hooks** - `useTracker`, `useTrackerContext` for easy integration
- ✅ **Provider Pattern** - `TrackerProvider` for managing multiple trackers across your app
- ✅ **Visibility Tracking** - `VisibilityTracker` component for impression tracking
- ✅ **TypeScript Support** - Full TypeScript definitions and type safety
- ✅ **Multiple Trackers** - Support for multiple tracker instances with unique keys

## Installation

```bash
# Install latest production version
npm install @rakutenanalytics/rat-react
```

## Quick Start

### Simple Hook Usage

```tsx
import React from 'react';
import { useTracker } from '@rakutenanalytics/rat-react';

function ProductPage() {
  // Initialize tracker with your account and service IDs
  const tracker = useTracker({ 
    accountId: 999,    // Replace with your account ID
    serviceId: 1       // Replace with your service ID
  });

  // Track page view on mount
  React.useEffect(() => {
    if (tracker) {
      tracker.sendPageviewEvent({
        params: {
          pageName: 'product'
        }
      });
    }
  }, [tracker]);

  const handleClick = () => {
    if (tracker) {
      tracker.sendClickEvent({
        params: {
          itemId: ['product-123']
        }
      });
    }
  };

  return (
    <div>
      <h1>Product Page</h1>
      <button onClick={handleClick}>
        Add to Cart
      </button>
    </div>
  );
}
```

### Provider Setup

Set up TrackerProvider at your application root for multiple trackers:

```tsx
// main.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { TrackerProvider, ReceiverEndpoint, type TrackerProviderConfig } from '@rakutenanalytics/rat-react'
import App from './App.tsx'

const trackers: TrackerProviderConfig[] = [
  { key: 'default', options: { accountId: 999, serviceId: 999 } },
  { key: 'custom', options: { accountId: 123, serviceId: 123, mainReceiver: ReceiverEndpoint.UK } }
];

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <TrackerProvider defaultTrackers={trackers}>
      <App />
    </TrackerProvider>
  </StrictMode>,
)
```

### Multiple Tracker Usage

```tsx
// Send events to different endpoints
import { useTrackerContext } from '@rakutenanalytics/rat-react';

function Home() {
  const { getTracker } = useTrackerContext();

  const defaultTracker = getTracker('default');
  const customTracker = getTracker('custom');

  const handleProductClick = () => {
    // Send click event to default endpoint (Japan)
    if (defaultTracker) {
      defaultTracker.sendClickEvent({
        params: {
          itemId: ['product-123']
        },
        customParams: {
          clktgt: 'product-button'
        }
      });
    }
  };

  const handlePurchaseEvent = () => {
    // Send conversion event to UK endpoint
    if (customTracker) {
      customTracker.sendClickEvent({
        cvEvents: { 
          purchase_gms: 3400, 
          purchase_order: 1, 
          purchase_shop: 2 
        },
      });
    }
  };

  return (
    <div>
      <button onClick={handleProductClick}>
        Track Product Click (Default Endpoint)
      </button>
      <button onClick={handlePurchaseEvent}>
        Track Purchase (UK Endpoint)
      </button>
    </div>
  );
}
```

## API Reference

### Hooks

#### `useTracker(options: TrackerOptions)`

Creates and returns a tracker instance for the specified account and service.

```tsx
import { useTracker } from '@rakutenanalytics/rat-react';

const tracker = useTracker({
  accountId: 999,
  serviceId: 999,
  mainReceiver?: ReceiverEndpoint,
  transportMethod?: TransportMethod,
});

tracker.sendPageviewEvent({
  params: {
    pageName: 'top'
  }
});
```

**Parameters:**
- `options: TrackerOptions` - Configuration object for the tracker

**Returns:**
- `Tracker | null` - Tracker instance (null during initialization)

#### `useTrackerContext()`

Accesses the tracker context provided by `TrackerProvider`. Must be used within a `TrackerProvider`.

```tsx
import { useTrackerContext } from '@rakutenanalytics/rat-react';

const { trackers, addTracker } = useTrackerContext();

// Get existing tracker
const mainTracker = trackers.get('main');

// Add new tracker at runtime
addTracker('newTracker', { accountId: 123, serviceId: 1 });
```

**Returns:**
- `trackers: Map<string, Tracker>` - Map of all available trackers
- `addTracker: (key: string, options: TrackerOptions) => void` - Function to add new trackers