npm package: @lightspeed/react-mixpanel-script
Description: React Mixpanel for SSR pages
Latest version: 0.4.13

# `@lightspeed/react-mixpanel-script`

[![npm version](https://badge.fury.io/js/%40lightspeed%2Freact-mixpanel-script.svg)](https://badge.fury.io/js/%40lightspeed%2Freact-mixpanel-script)

## Introduction

Add and use Mixpanel in your React application.

## Quick Start

1. Install the dependency in your webapp.

```sh
yarn add @lightspeed/react-mixpanel-script
```

2. In your serverside rendered document component, render the `<MixpanelScript />` component in the `<head />` of your document. It supports these properties:

| Property         | Type    | Description                                                                                                                                                                                                                          |
| ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `mixpanelApiKey` | string  | Your app's mixpanel API Key, typically passed through with an environment variable, for example `process.env.MIXPANEL_API_KEY`                                                                                                       |
| `nonce`          | string  | A unique identifier to reference the analytics script for security, install our [@lightspeed/express-csp-middleware](https://github.com/lightspeedretail/web-tools/tree/master/packages/express-csp-middleware) package to implement |
| `mixpanelConfig` | object? | Optional config to pass to the `mixpanel.init` function, see [available config options](https://developer.mixpanel.com/docs/javascript-full-api-reference#section-mixpanel-init)                                                     |

In a `Next.js` app with serverside rendering for example, use the component as follows:

```tsx
// app/_document.tsx
import React from 'react';
import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document';
import { MixpanelScript } from '@lightspeed/react-mixpanel-script';

type MyDocumentProps = {
  nonce: string;
};

export default class MyDocument extends Document<MyDocumentProps> {
  static async getInitialProps(ctx: NextDocumentContext) {
    // nonce comes from server.ts with our @lightspeed/express-csp-middleware package
    const { nonce } = (ctx.res as any).locals;
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps, nonce };
  }

  render() {
    return (
      <html>
        <Head>
          <title>Lightspeed - My App</title>
          <MixpanelScript
            nonce={this.props.nonce}
            mixpanelApiKey={process.env.MIXPANEL_API_KEY || ''}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}
```

1. In your application, add an `Analytics` component. This is used to provide and configure the Mixpanel context. It supports three arguments:

| Property      |  Type  | Description                                       |
| ------------- | :----: | ------------------------------------------------- |
| `appName`     | string | A unique identifier for your application          |
| `identity`    | string | A unique identifier for your user                 |
| `eventData`   | object | Data that will be sent with every generated event |
| `profileData` | object | Data that is defined for the analytic profile     |

```tsx
// app/components/Main/index.tsx
import { Analytics } from '@lightspeed/react-mixpanel-script';

export default () => (
  <Analytics
    appName="web-tools"
    identity="some-unique-identifier"
    eventData={{ myVar: 'data sent with every event' }}
    profileData={{ personId: 'some-unique-identifier' }}
  >
    <Application>
      <ApplicationHeader />
      <ApplicsationBody />
      <ApplicationFooter />
    </Application>
  </Analytics>
);
```

4. In your code, when you want to track an event, you can use the `useAnalaytics` hook to obtain the mixpanel context:

```tsx
// example_using_hook.tsx
import React from 'react';
import { useAnalytics } from '@lightspeed/react-mixpanel-script';

const MyComponent = () => {
  const mixpanel = useAnalytics();

  return (
    <button onClick={() => mixpanel.track('button clicked', { custom: 'something custom' })}>
      Click Me!
    </button>
  );
};
```

5. Alternatively, if your code is not structured to use hooks, you can use the convenience component `TrackClick`, which wraps over a component with or without a pre-existing click handler. Ultimately, this helper will be deprecated so it's suggested you use the `useAnalytics` hook instead.

```tsx
// example_track_click.tsx
import React from 'react';
import { TrackClick } from '@lightspeed/react-mixpanel-script';

const MyComponent = () => (
  <TrackClick event="button clicked" eventData={{ custom: 'something custom' }}>
    <button onClick={() => console.log('I am wrapped')}>Click Me!</button>;
  </TrackClick>
);
```

6. In your code, when you want to track any type of customer interaction, you can use the function `mixpanel`, which takes a callback with the Mixpanel object as a parameter:

```tsx
// component.tsx
import React from 'react';
import { mixpanel } from '@lightspeed/react-mixpanel-script';

export default class TrackedButton {
  render() {
    return <button onClick={() => mixpanel(m => m.track('button clicked'))}>Click Me!</button>;
  }
}
```

Please refer to the [Mixpanel documentation](https://mixpanel.com/help/reference/javascript-full-api-reference) to see all the functions that Mixpanel provides.