# Kpi (/docs/native/components/kpi)

<Preview id="kpi/anatomy" title={null} />

## Installation [#installation]

<ComponentInstall name="kpi" />

## Usage [#usage]

```tsx title="app/index.tsx"
import { Kpi } from "@/components/ui/kpi";
import { View } from "react-native";

const revenue = [31.2, 33.8, 32.9, 36.4, 35.1, 38.7, 41.2, 40.3, 43.9, 48.1];

export default function Example() {
  return (
    <View className="flex-1 justify-center p-4">
      <Kpi>
        <Kpi.Header>
          <Kpi.Title>Revenue</Kpi.Title>
        </Kpi.Header>
        <Kpi.Content>
          <Kpi.Stat>
            <Kpi.Value>$48,120</Kpi.Value>
            <Kpi.Trend caption="vs last month" value={7.8} />
          </Kpi.Stat>
          <Kpi.Sparkline data={revenue} />
        </Kpi.Content>
      </Kpi>
    </View>
  );
}
```

## Anatomy [#anatomy]

```tsx
<Kpi colorIndex={1} goodDirection="up">
  <Kpi.Header>
    <Kpi.Icon />
    <Kpi.Title />
    <Kpi.Action />
  </Kpi.Header>
  <Kpi.Content layout="below">
    <Kpi.Stat>
      <Kpi.Value />
      <Kpi.Trend />
    </Kpi.Stat>
    <Kpi.Sparkline />
  </Kpi.Content>
  <Kpi.Footer />
</Kpi>

<Kpi.Group orientation="horizontal" separated>…</Kpi.Group>
```

A `Kpi` is a [`Card`](/docs/native/components/card): it takes the card's four fills and three sizes, and
the header and content sit on the card's own inset, so the number lines up with the footer beneath it.
`Kpi.Stat` holds the value and its change together — they are one fact in two lines, and the card's gap is
for the space between facts.

## Which way is good [#which-way-is-good]

Colour comes from what the movement *means*, not from its sign. A fall in churn, refunds or latency is good
news, and is drawn as good news — say so once on the card with `goodDirection` and every trend inside
follows. `"none"` is for a number that is neither, like a headcount.

<Preview id="kpi/good-direction" />

```tsx
<Kpi goodDirection="up">
  <Kpi.Trend value={7.8} />
</Kpi>

<Kpi goodDirection="down">
  <Kpi.Trend value={-8.4} />
</Kpi>

<Kpi goodDirection="none">
  <Kpi.Trend value={2.2} />
</Kpi>
```

The sign is the direction, so there is no direction prop to keep in step with the value. A movement no
larger than `threshold` counts as none, and a value that is not finite — a change against a zero baseline
— is flat rather than news of either kind.

## Trend variants [#trend-variants]

`text` is a line of colour under the number. `badge` puts a pill round it, with an arrow that says the
direction again in a shape — for a card busy enough that a bare line of colour is lost in it.

```tsx
<Kpi.Trend caption="vs last month" value={12.4} />
<Kpi.Trend value={-3.1} variant="badge" />
<Kpi.Trend format={(value) => `+${value} users`} value={120} />
```

The default prints one decimal place with an explicit sign and a typographic minus, so a column of changes
lines up on the sign. A screen reader hears one string — "Up 7.8 percent, vs last month".

## Sizes [#sizes]

The card's `sm`, `md` and `lg`. One axis moves the inset, the value's scale, the change and the
sparkline's height together.

```tsx
<Kpi size="sm">…</Kpi>
<Kpi size="lg">…</Kpi>
```

## Inline [#inline]

`layout="inline"` sets the sparkline in a fixed 128pt column beside the number, unfilled. A stack of cards
has labels of every length, and a fixed column keeps the shapes lined up down the right-hand edge.

<Preview id="kpi/inline" />

```tsx
<Kpi size="sm">
  <Kpi.Content layout="inline">
    <Kpi.Stat>
      <Kpi.Title>Orders</Kpi.Title>
      <Kpi.Value>1,284</Kpi.Value>
      <Kpi.Trend value={4.1} />
    </Kpi.Stat>
    <Kpi.Sparkline data={orders} />
  </Kpi.Content>
</Kpi>
```

## Sparkline [#sparkline]

A `Chart` line with no grid, no axes and no padding, in the card's series colour — `colorIndex` on the
card picks the slot of the theme's ramp, and `Kpi.Icon` takes the same one. It takes a bare list of numbers,
or rows with an `xKey` and a `yKey`. Its y bounds are the data's own, padded a tenth each way, so the peak
and trough are never drawn half off the frame.

```tsx
<Kpi.Sparkline data={[3, 4, 3.6, 5, 4.8, 6]} />
<Kpi.Sparkline data={rows} xKey="day" yKey="visits" />
<Kpi.Sparkline colorIndex={4} data={values} filled={false} strokeWidth={1.5} />
```

## Scrub [#scrub]

Hold the sparkline and drag. A dot rides the line and the KPI's `activeIndex` follows the finger, going
back to `null` when it lets go. `useKpi()` reads it, so a part of your own prints the scrubbed point in
place of the latest.

<Preview id="kpi/scrub" />

```tsx
function ScrubbedValue() {
  const { activeIndex } = useKpi();
  return <Kpi.Value>{format(values[activeIndex ?? values.length - 1])}</Kpi.Value>;
}

<Kpi>
  <Kpi.Content>
    <Kpi.Stat>
      <ScrubbedValue />
    </Kpi.Stat>
    <Kpi.Sparkline data={values} />
  </Kpi.Content>
</Kpi>
```

It is controllable like any other state: pass `activeIndex` and `onActiveIndexChange` to hold it yourself,
or `defaultActiveIndex` to seed it. `interactive={false}` turns the scrub off — for a sparkline inside a
`Pressable`, say.

```tsx
const [activeIndex, setActiveIndex] = useState<number | null>(null);

<Kpi activeIndex={activeIndex} onActiveIndexChange={setActiveIndex}>…</Kpi>
```

## Loading [#loading]

`isLoading` swaps the value, the change and the sparkline for placeholders of their own size and marks the
card busy, so nothing jumps when the data lands.

```tsx
<Kpi isLoading={isFetching}>…</Kpi>
```

## Groups [#groups]

`Kpi.Group` lays several metrics out in a row or a column. In a row each takes an equal share of the width.
`separated` sets them on one surface with a rule between each — one panel rather than several that happen
to sit side by side.

<Preview id="kpi/group" />

```tsx
<Kpi.Group orientation="horizontal" separated>
  <Kpi size="sm">…</Kpi>
  <Kpi goodDirection="down" size="sm">…</Kpi>
</Kpi.Group>
```

## Composition [#composition]

A KPI is layout, like the card it is built on. One that selects is a `Pressable` around it, which keeps the
role and the haptic at the call site that knows what the press means.

<Preview id="kpi/dashboard" />

```tsx
<Pressable
  accessibilityRole="radio"
  accessibilityState={{ checked: isSelected }}
  haptic="selection"
  onPress={() => setMetric("revenue")}
>
  <Kpi className={isSelected ? "border-primary" : undefined} size="sm">
    <Kpi.Content layout="inline">
      <Kpi.Stat>
        <Kpi.Title>Revenue</Kpi.Title>
        <Kpi.Value>$48,120</Kpi.Value>
        <Kpi.Trend value={7.8} />
      </Kpi.Stat>
      <Kpi.Sparkline data={revenue} interactive={false} />
    </Kpi.Content>
  </Kpi>
</Pressable>
```

## API Reference [#api-reference]

### Kpi [#kpi]

Extends [`Card`](/docs/native/components/card)'s props.

<TypeTable
  type={{
    colorIndex: {
      type: "1 | 2 | 3 | 4 | 5",
      default: "1",
      description: "The slot of the theme's series ramp the sparkline and the icon take.",
    },
    goodDirection: {
      type: '"up" | "down" | "none"',
      default: '"up"',
      description: "Which way is the good news. Every trend inside follows it unless it overrides it.",
    },
    isLoading: {
      type: "boolean",
      default: "false",
      description: "Placeholders for the value, the change and the sparkline; the card is marked busy.",
    },
    activeIndex: { type: "number | null", description: "The scrubbed sparkline point, controlled." },
    defaultActiveIndex: { type: "number | null", default: "null", description: "The scrubbed point to start from." },
    onActiveIndexChange: {
      type: "(index: number | null) => void",
      description: "Called as the scrub moves between points, and with `null` when it lets go.",
    },
    variant: {
      type: '"default" | "secondary" | "tertiary" | "transparent"',
      description: "The card's fill. Omitted, it steps inside another surface.",
    },
    size: { type: '"sm" | "md" | "lg"', default: '"md"' },
  }}
/>

### Kpi.Header [#kpiheader]

The top row — an icon, the title, and an action pushed to the end. Extends `ViewProps`.

### Kpi.Icon [#kpiicon]

A square tinted in the series colour. An unstyled `Icon` inside takes that colour and a size to match.
Extends `ViewProps`.

### Kpi.Title [#kpititle]

The metric's name, muted, on one line. Extends `Text`'s props.

### Kpi.Action [#kpiaction]

The header's trailing end — a menu, a filter, a link. Extends `ViewProps`.

### Kpi.Content [#kpicontent]

Extends `ViewProps`.

<TypeTable
  type={{
    layout: {
      type: '"below" | "inline"',
      default: '"below"',
      description: "`inline` sets the sparkline in a fixed column beside the number.",
    },
  }}
/>

### Kpi.Stat [#kpistat]

The value and its change, stacked as one fact. Extends `ViewProps`.

### Kpi.Value [#kpivalue]

The number, formatted by you, on one line. Extends `Text`'s props.

### Kpi.Trend [#kpitrend]

Extends `ViewProps`.

<TypeTable
  type={{
    value: {
      type: "number",
      required: true,
      description: "How much it moved, as a percentage. The sign is the direction.",
    },
    variant: { type: '"text" | "badge"', default: '"text"' },
    caption: { type: "string", description: "What it is compared against — read after the change." },
    format: { type: "(value: number) => string", description: "Writes the number yourself." },
    goodDirection: { type: '"up" | "down" | "none"', description: "Overrides the KPI's own." },
    threshold: { type: "number", default: "0", description: "A movement no larger than this counts as none." },
  }}
/>

### Kpi.Sparkline [#kpisparkline]

<TypeTable
  type={{
    data: {
      type: "number[] | ChartDatum[]",
      required: true,
      description: "A list of numbers, or rows read with `xKey` and `yKey`.",
    },
    xKey: { type: "string", description: "With rows: the field that orders them." },
    yKey: { type: "string", description: "With rows: the field to plot." },
    colorIndex: { type: "1 | 2 | 3 | 4 | 5", description: "Overrides the KPI's." },
    color: { type: "string", description: "A token or a literal, over the series colour." },
    filled: { type: "boolean", description: "Defaults on below the number and off beside it." },
    strokeWidth: { type: "number", default: "2" },
    interactive: { type: "boolean", default: "true", description: "Hold and drag to scrub." },
    formatValue: {
      type: "(value: number) => string",
      description: "Formats the first and last point for the screen-reader summary.",
    },
  }}
/>

### Kpi.Footer [#kpifooter]

`Card.Footer`, with bare text set as a muted caption. `variant="band"` sets it into the card.

### Kpi.Group [#kpigroup]

Extends `ViewProps`.

<TypeTable
  type={{
    orientation: { type: '"horizontal" | "vertical"', default: '"vertical"' },
    separated: {
      type: "boolean",
      default: "false",
      description: "One surface with a rule between the metrics, rather than cards spaced apart.",
    },
  }}
/>

### useKpi [#usekpi]

Reads the enclosing KPI, for a part of your own. Throws outside a `Kpi`.

<TypeTable
  type={{
    activeIndex: { type: "number | null", description: "The scrubbed point, or `null`." },
    setActiveIndex: { type: "(index: number | null) => void" },
    size: { type: '"sm" | "md" | "lg"' },
    colorIndex: { type: "1 | 2 | 3 | 4 | 5" },
    goodDirection: { type: '"up" | "down" | "none"' },
    isLoading: { type: "boolean" },
  }}
/>
