# KPI with comparison

A headline figure with its change against a comparison period, coloured by direction.

- Component: `<KpiNumberComparison />`, imported from `em-kit`
- Required props: `measure`, `primaryDateRange`, `results`, `resultsComparison` and `comparisonDateRange`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/kpi-number-comparison
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/kpi-number-comparison/playground

## Install

```bash
npm install em-kit
pnpm add em-kit   # or, with pnpm
yarn add em-kit   # or, with yarn
bun add em-kit   # or, with bun
```

`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `<ChartsProvider>` once: without it every chart throws `EmKit components must be rendered inside <ChartsProvider>.` Every example on this page includes `<ChartsProvider>` so that it runs on its own: if your app already has one, delete it from the example. The card fills its parent, so the parent needs a height; the number scales to fit. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.

## Usage

```tsx
import { ChartsProvider, KpiNumberComparison, measure, results } from 'em-kit';

const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', decimalPlaces: 0 },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ width: 360, height: 200 }}>
      <KpiNumberComparison
        title="Revenue, last 30 days"
        measure={revenue}
        results={results(currentRows)}
        resultsComparison={results(previousRows)}
        comparisonPeriod="Previous period"
        primaryDateRange={currentRange}
        comparisonDateRange={previousRange}
      />
    </div>
  </ChartsProvider>
);

const currentRange = {
  from: new Date('2026-06-01'),
  to: new Date('2026-06-30'),
};
const previousRange = {
  from: new Date('2026-05-02'),
  to: new Date('2026-05-31'),
};

const currentRows = [{ revenue: 160625 }];
const previousRows = [{ revenue: 143757 }];
```

## States

The card draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.

## Examples

### Change as a percentage

The change as a percentage of the earlier figure, instead of an amount in the measure’s own format. `displayChangeAsPercentage` switches to a percentage, to one decimal place.

```tsx
import { ChartsProvider, KpiNumberComparison, measure, results } from 'em-kit';

const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', decimalPlaces: 0 },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ width: 360, height: 200 }}>
      <KpiNumberComparison
        title="Revenue, last 30 days"
        measure={revenue}
        results={results(currentRows)}
        resultsComparison={results(previousRows)}
        comparisonPeriod="Previous period"
        primaryDateRange={currentRange}
        comparisonDateRange={previousRange}
        displayChangeAsPercentage
      />
    </div>
  </ChartsProvider>
);

const currentRange = {
  from: new Date('2026-06-01'),
  to: new Date('2026-06-30'),
};
const previousRange = {
  from: new Date('2026-05-02'),
  to: new Date('2026-05-31'),
};

const currentRows = [{ revenue: 160625 }];
const previousRows = [{ revenue: 143757 }];
```

### Lower is better

For costs, churn or response times: a rise shows red and a fall shows green. `reversePositiveNegativeColors` swaps the colours. `reverseTrendDirection={false}` keeps the arrow pointing the way the number moved; without it the arrow flips with the colours.

```tsx
import { ChartsProvider, KpiNumberComparison, measure, results } from 'em-kit';

const churnRate = measure({
  name: 'churn_rate',
  title: 'Churn rate',
  inputs: { suffix: '%', decimalPlaces: 1 },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ width: 360, height: 200 }}>
      <KpiNumberComparison
        title="Churn rate, last 30 days"
        measure={churnRate}
        results={results(currentRows)}
        resultsComparison={results(previousRows)}
        comparisonPeriod="Previous period"
        primaryDateRange={currentRange}
        comparisonDateRange={previousRange}
        reversePositiveNegativeColors
        reverseTrendDirection={false}
      />
    </div>
  </ChartsProvider>
);

const currentRange = {
  from: new Date('2026-06-01'),
  to: new Date('2026-06-30'),
};
const previousRange = {
  from: new Date('2026-05-02'),
  to: new Date('2026-05-31'),
};

const currentRows = [{ churn_rate: 2.5 }];
const previousRows = [{ churn_rate: 2.7 }];
```

### Two decimals

A percentage change to two decimal places, for metrics that move by fractions of a percent. `percentageDecimalPlaces` only applies with `displayChangeAsPercentage`.

```tsx
import { ChartsProvider, KpiNumberComparison, measure, results } from 'em-kit';

const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', decimalPlaces: 0 },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ width: 360, height: 200 }}>
      <KpiNumberComparison
        title="Revenue, last 30 days"
        measure={revenue}
        results={results(currentRows)}
        resultsComparison={results(previousRows)}
        comparisonPeriod="Previous period"
        primaryDateRange={currentRange}
        comparisonDateRange={previousRange}
        displayChangeAsPercentage
        percentageDecimalPlaces={2}
      />
    </div>
  </ChartsProvider>
);

const currentRange = {
  from: new Date('2026-06-01'),
  to: new Date('2026-06-30'),
};
const previousRange = {
  from: new Date('2026-05-02'),
  to: new Date('2026-05-31'),
};

const currentRows = [{ revenue: 160625 }];
const previousRows = [{ revenue: 143757 }];
```

## Props

Required props come first. A blank default means the prop is unset unless you pass it.

| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `measure` | `Measure` | yes |  | The number to show and compare. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `primaryDateRange` | `TimeRange` | yes |  | The dates `results` covers: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. Only read to work out the comparison dates for `setComparisonDateRange`. |
| `results` | `DataResponse` | yes |  | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `resultsComparison` | `DataResponse` | yes |  | Rows for the comparison period, with the same keys as `results`. |
| `comparisonDateRange` | `TimeRange` | yes |  | The dates `resultsComparison` covers: `{ from: Date, to: Date }`, with an optional `relativeTimeString` naming a preset. Without it the change is not shown. |
| `changeFontSize` | `number` | no |  | Font size of the change line in pixels. |
| `comparisonPeriod` | `string` | no |  | Names the comparison under the number (“vs previous period”, translated). One of `"Previous period"`, `"Previous week"`, `"Previous month"`, `"Previous quarter"`, `"Previous year"`, `"Same period last week"`, `"Same period last month"`, `"Same period last quarter"`, `"Same period last year"`; any other string leaves the name empty. |
| `displayChangeAsPercentage` | `boolean` | no | `false` | Show the change as a percentage instead of a difference. |
| `fontSize` | `number` | no |  | Font size of the headline number in pixels. By default it grows and shrinks to fit the card. |
| `reversePositiveNegativeColors` | `boolean` | no | `false` | Colour an increase as bad and a decrease as good, for costs or churn. |
| `reverseTrendDirection` | `boolean` | no |  | Point the trend arrow the other way. When unset, the arrow follows `reversePositiveNegativeColors`. |
| `percentageDecimalPlaces` | `number` | no | `1` | Decimal places on the percentage change. |
| `displayNullAs` | `string` | no |  | Text shown where a value is null, for example `"–"`. |
| `setComparisonDateRange` | `(dateRange: TimeRange) => void` | no |  | If set, the card works out the comparison dates from `primaryDateRange` and `comparisonPeriod` and calls this with them, so you can query them. When it cannot work them out, it calls this with no range. |
| `title` | `string` | no |  | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no |  | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no |  | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |

```ts
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```

Each is exported from `em-kit` as a type, for example `import type { TimeRange } from 'em-kit'`.

A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.

## Field options

Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them.
