# Scrollable table

An infinite-scroll table: you serve pages of 50 rows and it appends each as the reader scrolls.

- Component: `<TableScrollable />`, imported from `em-kit`
- Required props: `dimensionsAndMeasures` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/table-scrollable
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/table-scrollable/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 and scrolls inside it, so the parent needs a height, unless `heightMode="auto"` lets the card grow to fit its rows. 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 { useMemo, useState } from 'react';
import {
  ChartsProvider,
  TableScrollable,
  dimension,
  measure,
  results,
} from 'em-kit';
import type { TableScrollableState } from 'em-kit';

const startDate = dimension({
  name: 'startDate',
  title: 'Start date',
  type: 'time',
  granularity: 'day',
});
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', decimalPlaces: 0 },
});
const customers = measure({ name: 'customers', title: 'Customers' });
// Identifies the query: when it changes, the table starts again from page 0
const filters = { search: '' };

export const Example = () => {
  const [state, setState] = useState<TableScrollableState>({
    page: 0,
    isLoadingDownloadData: false,
  });
  // Stand-in for your API. Memoised: the table appends every new array.
  const sorted = useMemo(() => sortRows(rows, state.sort), [state.sort]);
  return (
    <ChartsProvider>
      <div style={{ height: 360 }}>
        <TableScrollable
          title="Revenue and customers by day"
          dimensionsAndMeasures={[startDate, revenue, customers]}
          clickDimension={startDate}
          results={results(sorted)}
          // Every row, unpaged: the card menu’s downloads wait for it.
          allResults={results(sorted)}
          resetKey={filters}
          state={state}
          setState={setState}
        />
      </div>
    </ChartsProvider>
  );
};

const rows: Record<string, string | number>[] = [
  { startDate: '2026-01-01T00:00:00.000', revenue: 4709, customers: 15 },
  { startDate: '2026-01-02T00:00:00.000', revenue: 4722, customers: 16 },
  { startDate: '2026-01-03T00:00:00.000', revenue: 3246, customers: 10 },
  { startDate: '2026-01-04T00:00:00.000', revenue: 2890, customers: 9 },
  { startDate: '2026-01-05T00:00:00.000', revenue: 4631, customers: 14 },
  { startDate: '2026-01-06T00:00:00.000', revenue: 4762, customers: 14 },
  { startDate: '2026-01-07T00:00:00.000', revenue: 4563, customers: 14 },
  { startDate: '2026-01-08T00:00:00.000', revenue: 5046, customers: 17 },
  { startDate: '2026-01-09T00:00:00.000', revenue: 4492, customers: 14 },
  { startDate: '2026-01-10T00:00:00.000', revenue: 2989, customers: 11 },
  { startDate: '2026-01-11T00:00:00.000', revenue: 3247, customers: 10 },
  { startDate: '2026-01-12T00:00:00.000', revenue: 4395, customers: 15 },
  { startDate: '2026-01-13T00:00:00.000', revenue: 4204, customers: 14 },
  { startDate: '2026-01-14T00:00:00.000', revenue: 4949, customers: 13 },
  { startDate: '2026-01-15T00:00:00.000', revenue: 4675, customers: 15 },
];

// The rows in the order the table asks for. With more rows, serve 50 a page by
// state.page; a shorter page ends the scroll.
const sortRows = (data: typeof rows, sort: TableScrollableState['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));
};
```

- Sorting, or a new `resetKey`, starts again from page 0.

## 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

### Auto height

The card grows to fit every row instead of scrolling: for printable reports and embedded summaries. `heightMode="auto"`: pass all the rows at once (up to your own cap) with `results.total`, and the table says when rows were left out.

```tsx
import { useMemo, useState } from 'react';
import {
  ChartsProvider,
  TableScrollable,
  dimension,
  measure,
  results,
} from 'em-kit';
import type { TableScrollableState } from 'em-kit';

const startDate = dimension({
  name: 'startDate',
  title: 'Start date',
  type: 'time',
  granularity: 'month',
});
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', decimalPlaces: 0 },
});
const customers = measure({ name: 'customers', title: 'Customers' });
// Identifies the query: when it changes, the table starts again from page 0
const filters = { search: '' };

export const Example = () => {
  const [state, setState] = useState<TableScrollableState>({
    page: 0,
    isLoadingDownloadData: false,
  });
  // Stand-in for your API. Memoised: the table appends every new array.
  const sorted = useMemo(() => sortRows(rows, state.sort), [state.sort]);
  return (
    <ChartsProvider>
      <TableScrollable
        title="Revenue and customers by month"
        dimensionsAndMeasures={[startDate, revenue, customers]}
        clickDimension={startDate}
        results={results(sorted)}
        // Every row, unpaged: the card menu’s downloads wait for it.
        allResults={results(sorted)}
        resetKey={filters}
        state={state}
        setState={setState}
        heightMode="auto"
      />
    </ChartsProvider>
  );
};

const rows: Record<string, string | number>[] = [
  { startDate: '2026-01-01T00:00:00.000', revenue: 131229, customers: 406 },
  { startDate: '2026-02-01T00:00:00.000', revenue: 116685, customers: 385 },
  { startDate: '2026-03-01T00:00:00.000', revenue: 141619, customers: 469 },
  { startDate: '2026-04-01T00:00:00.000', revenue: 138438, customers: 410 },
  { startDate: '2026-05-01T00:00:00.000', revenue: 148882, customers: 428 },
  { startDate: '2026-06-01T00:00:00.000', revenue: 160625, customers: 476 },
];

// The rows in the order the table asks for. With more rows, serve 50 a page by
// state.page; a shorter page ends the scroll.
const sortRows = (data: typeof rows, sort: TableScrollableState['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 `"–"`. |
| `showIndex` | `boolean` | no | `true` | Number the rows. |
| `state` | `TableScrollableState` | 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`. |
| `onRowClicked` | `(rowDimensionValue: TableScrollableOnRowClickArg) => void` | no |  | Called with the clicked row’s `clickDimension` value. |
| `setState` | `(value: SetStateAction<TableScrollableState>) => 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"]` | Which entries the card menu offers. Pass `[]` for none. |
| `resetKey` | `unknown` | no |  | Any value that identifies the current query, such as your filters. When it changes (compared by value), the table goes back to the top and starts again from page 0. |
| `heightMode` | `"fixed" \| "auto"` | no | `"fixed"` | `"fixed"` scrolls inside the card and loads pages as the reader scrolls. `"auto"` grows the card to fit every row you pass. |

```ts
type TableScrollableState = { page: number; pageSize?: number | undefined; sort?: { id: string; direction: "asc" | "desc"; } | undefined; isLoadingDownloadData: boolean; heightMode?: "fixed" | "auto" | undefined; }
type TableScrollableOnRowClickArg = { 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 { TableScrollableState } 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. `TableScrollable` 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. |
| `displayFormat` | `'Markdown' \| 'Json'` | `dimensionsAndMeasures` |  | Render the cell’s text as Markdown, or as indented JSON. |
| `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 and each cell’s copy button, scrolling the table to keep the focus in view. |
| `Enter` or `Space` | Column header | Sorts ascending, then descending, then clears the sort. |
| `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).
