Skip to main content

React Clarify

React Clarify is a library that allows you to instrument your React components for declarative user tracking and analytics.

Installation

npm install react-clarify

Usage

React Clarify works by defining the tracking context in a cascading manner. Let's see with an example:

import React from 'react';
import { ConsoleTrackingHandler, TrackEvent, TrackingProvider } from 'react-clarify';

export default function Example() {
return (
<TrackingProvider data={{ user: { name: 'johndoe', id: '123456' }, company: 'acme' }}>
<ConsoleTrackingHandler level="info" transform={JSON.stringify}>
<TrackingProvider data={{ page: 'Home Page' }}>
<p>Clicking the button will log a message to the console and send a tracking event.</p>

<TrackEvent event="click" data={{ element: 'My button' }}>
<button type="button">Click me</button>
</TrackEvent>
</TrackingProvider>
</ConsoleTrackingHandler>
</TrackingProvider>
);
}

In summary, there are 3 group of components you need to know about:

  • TrackingProvider is a context provider for defining the data that will be passed to the tracking handler. data for the nested TrackingProvider will be merged together.
  • TrackingHandler is for defining a callback function that will be called when a tracking event is fired. ConsoleTrackingHandler is a predefined handler for simply logging the tracked data to the console. Handlers can be nested to call them all when a tacking event occurs.
  • TrackEvent and is used to fire a tracking event when a DOM event occurs. It's children must be a single React component that takes a ref.
    • As an alternative to TrackEvent, TrackCallback can be used to fire tracking events using not just DOM events, but any arbitrary callback function. It can be used like <TrackCallback callback="onClick">.
    • useTrack hook can be used to get a function that can be used to fire a tracking event that can be called manually.

Let's see the result of the example above:

http://localhost:3000

Clicking the button will log a message to the console and send a tracking event.