# Paginated table

A controlled table: you own paging and sorting and pass in the current page of rows.

- Component: `<TablePaginated />`, imported from `em-kit`
- Required props: `dimensionsAndMeasures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/table-paginated
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/table-paginated/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 table fills its parent, so the parent needs a height: a page holds as many rows as fit it, reported as `state.pageSize`. 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 { useState } from 'react';
import {
  ChartsProvider,
  TablePaginated,
  dimension,
  measure,
  results,
} from 'em-kit';
import type { TablePaginatedState } from 'em-kit';

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

export const Example = () => {
  const [state, setState] = useState<TablePaginatedState>({
    page: 0,
    isLoadingDownloadData: false,
  });
  // Stand-in for your API: the page the table asks for, in its sort order.
  const { page, pageSize = 10, sort } = state;
  const sorted = sortRows(rows, sort);
  const pageRows = sorted.slice(page * pageSize, (page + 1) * pageSize);
  return (
    <ChartsProvider>
      <div style={{ height: 370 }}>
        <TablePaginated
          title="Revenue and customers by region"
          dimensionsAndMeasures={[region, revenue, customers]}
          results={results(pageRows)}
          totalResults={{ isLoading: false, total: rows.length }}
          // Every row, unpaged: the card menu’s downloads wait for it.
          allResults={results(sorted)}
          state={state}
          setState={setState}
        />
      </div>
    </ChartsProvider>
  );
};

const rows: Record<string, string | number>[] = [
  { region: 'North America', revenue: 324606, customers: 985 },
  { region: 'Europe', revenue: 221197, customers: 709 },
  { region: 'Asia Pacific', revenue: 146411, customers: 451 },
  { region: 'Latin America', revenue: 84145, customers: 240 },
  { region: 'Middle East', revenue: 61120, customers: 188 },
];

// The rows in the order the table asks for: a column, ascending or descending.
const sortRows = (data: typeof rows, sort: TablePaginatedState['sort']) => {
  if (!sort) return data;
  const sign = sort.direction === 'desc' ? -1 : 1;
  return [...data].sort((a, b) => (a[sort.id]! > b[sort.id]! ? sign : -sign));
};
```

## States

The table 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

### Formatted columns

Formatting set per column: the names in bold, and the first measure in compact numbers, with thousands as K. `tableCellStyle` and `abbreviateLargeNumber` are field options on each column’s dimension or measure.

```tsx
import { useState } from 'react';
import {
  ChartsProvider,
  TablePaginated,
  dimension,
  measure,
  results,
} from 'em-kit';
import type { TablePaginatedState } from 'em-kit';

const region = dimension({
  name: 'region',
  title: 'Region',
  inputs: { tableCellStyle: 'Bold' },
});
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', abbreviateLargeNumber: true },
});
const customers = measure({ name: 'customers', title: 'Customers' });

export const Example = () => {
  const [state, setState] = useState<TablePaginatedState>({
    page: 0,
    isLoadingDownloadData: false,
  });
  // Stand-in for your API: the page the table asks for, in its sort order.
  const { page, pageSize = 10, sort } = state;
  const sorted = sortRows(rows, sort);
  const pageRows = sorted.slice(page * pageSize, (page + 1) * pageSize);
  return (
    <ChartsProvider>
      <div style={{ height: 370 }}>
        <TablePaginated
          title="Revenue and customers by region"
          dimensionsAndMeasures={[region, revenue, customers]}
          results={results(pageRows)}
          totalResults={{ isLoading: false, total: rows.length }}
          // Every row, unpaged: the card menu’s downloads wait for it.
          allResults={results(sorted)}
          state={state}
          setState={setState}
        />
      </div>
    </ChartsProvider>
  );
};

const rows: Record<string, string | number>[] = [
  { region: 'North America', revenue: 324606, customers: 985 },
  { region: 'Europe', revenue: 221197, customers: 709 },
  { region: 'Asia Pacific', revenue: 146411, customers: 451 },
  { region: 'Latin America', revenue: 84145, customers: 240 },
  { region: 'Middle East', revenue: 61120, customers: 188 },
];

// The rows in the order the table asks for: a column, ascending or descending.
const sortRows = (data: typeof rows, sort: TablePaginatedState['sort']) => {
  if (!sort) return data;
  const sign = sort.direction === 'desc' ? -1 : 1;
  return [...data].sort((a, b) => (a[sort.id]! > b[sort.id]! ? sign : -sign));
};
```

## Props

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

| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimensionsAndMeasures` | `DimensionOrMeasure[]` | yes |  | The table columns, in order. Dimensions show as text, measures as formatted numbers. |
| `results` | `DataResponse` | yes |  | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `allResults` | `DataResponse` | no |  | Every row, unpaged, for the downloads in the card menu. A download waits until this is set and not loading, so without it the menu spins for good. `state.isLoadingDownloadData` turns `true` when a reader asks, if you would rather fetch only then. |
| `clickDimension` | `Dimension` | no |  | The dimension whose value `onRowClicked` receives. Rows are only clickable when it is set. |
| `displayNullAs` | `string` | no |  | Text shown where a value is null, for example `"–"`. |
| `pageSize` | `number` | no |  | Rows on a page. Left out, the table shows as many rows as fit its height. Either way it reports the number in `state.pageSize`. Give the card room for the rows, about 40 pixels each, or they scroll inside it. |
| `showIndex` | `boolean` | no | `true` | Number the rows. |
| `state` | `TablePaginatedState` | no |  | Paging and sorting, controlled: keep it in `useState` and build your query from it. Without `state` and `setState` the table cannot page or sort; downloads need only `allResults`. |
| `totalResults` | `DataResponse` | no |  | A result carrying only `total`, the number of rows across all pages. The page count is worked out from it. |
| `onRowClicked` | `(rowDimensionValue: TablePaginatedOnRowClickArg) => void` | no |  | Called with the clicked row’s `clickDimension` value. |
| `setState` | `(value: SetStateAction<TablePaginatedState>) => void` | no |  | A function that stores the new state, such as the setter from `useState`. Called when the reader pages, sorts or downloads, and when the page size is first known or changes. |
| `componentName` | `string` | no |  | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no |  | An id included in the same events, to tell two instances apart. |
| `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 TablePaginatedState = { page: number; pageSize?: number | undefined; sort?: { id: string; direction: "asc" | "desc"; } | undefined; isLoadingDownloadData: boolean; }
type TablePaginatedOnRowClickArg = { dimensionValue: string | null | undefined; dimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```

Each is exported from `em-kit` as a type, for example `import type { TablePaginatedState } 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. `TablePaginated` also reads:

| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `width` | `number` | `dimensionsAndMeasures` |  | The column’s width in pixels. |
| `align` | `'left' \| 'center' \| 'right'` | `dimensionsAndMeasures` |  | Align the column’s cells left, centre or right. |
| `tableCellStyle` | `'Bold' \| 'Italic' \| 'Positive vs Negative'` | `dimensionsAndMeasures` |  | Style the column’s cells. `Positive vs Negative` colours values above zero as good and the rest as bad. |

## Keyboard

| Key | Where | What it does |
|---|---|---|
| `Tab`, `Shift` + `Tab` | Table | Moves between the column headers, each cell’s copy button and the page buttons. |
| `Enter` or `Space` | Column header | Sorts ascending, then descending, then clears the sort. |
| `Enter` or `Space` | Page button | Goes to the first, previous, next or last page. |
| `Enter` or `Space` | Copy button in a cell | Copies the cell’s value. The button shows on hover and while focus is in its cell. |

The card menu’s keys, and what is still missing, are in [Accessibility](/docs/accessibility.md#keyboard).
