Components · Tables

Paginated table

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

Open in playground

Preview

Revenue and customers by region

#
1North America$324,606985
2Europe$221,197709
3Asia Pacific$146,411451
4Latin America$84,145240
5Middle East$61,120188
Page 1 of ?

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));
};

Install with npm install em-kit. Needs <ChartsProvider> once and a parent with a height: Quick start.

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.

tsxDiffers from Usage
Show full code (63 lines)
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));
};
const region = dimension({
  name: 'region',
  title: 'Region',
  inputs: { tableCellStyle: 'Bold' },
});
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', abbreviateLargeNumber: true },
});

<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}
/>

Props

PropTypeDefaultDescription
dimensionsAndMeasuresrequiredDimensionOrMeasure[]The table columns, in order. Dimensions show as text, measures as formatted numbers.
resultsrequiredDataResponseYour query’s state: { isLoading, data, error }, where data is your rows. results(rows) builds it from an array.
allResultsDataResponseEvery 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.
clickDimensionDimensionThe dimension whose value onRowClicked receives. Rows are only clickable when it is set.
displayNullAsstringText shown where a value is null, for example "–".
pageSizenumberRows 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.
showIndexbooleantrueNumber the rows.
stateTablePaginatedStatePaging 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.TablePaginatedState = { page: number; pageSize?: number | undefined; sort?: { id: string; direction: "asc" | "desc"; } | undefined; isLoadingDownloadData: boolean; }
totalResultsDataResponseA result carrying only total, the number of rows across all pages. The page count is worked out from it.
onRowClicked(rowDimensionValue: TablePaginatedOnRowClickArg) => voidCalled with the clicked row’s clickDimension value.TablePaginatedOnRowClickArg = { dimensionValue: string | null | undefined; dimensionTimeRange: TimeRange; }
setState(value: SetStateAction<TablePaginatedState>) => voidA 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.
componentNamestringA name for this component, included in the interaction events it dispatches on the DOM, for your analytics.
trackingIdstringAn id included in the same events, to tell two instances apart.
titlestringThe card’s title. A "key|fallback" string is looked up in your translations.
descriptionstringSmaller text under the title. Translates like title.
tooltipstringText for an info icon beside the title.
hideMenubooleanfalseHide the card’s header: the title, description and menu.
menuOptions("csv" | "xlsx" | "png" | "maximize")[]["csv", "xlsx", "png", "maximize"]Which entries the card menu offers. Pass [] for none.

A blank default means the prop is unset unless you pass it.

TypeDefinition
TimeRange{ from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefinedWhat a click’s TimeRange holds: Events.

Field options

Set in a field’s inputs, beside the common options:

OptionTypeSet onDescription
widthnumberdimensionsAndMeasuresThe column’s width in pixels.
align'left' | 'center' | 'right'dimensionsAndMeasuresAlign the column’s cells left, centre or right.
tableCellStyle'Bold' | 'Italic' | 'Positive vs Negative'dimensionsAndMeasuresStyle the column’s cells. Positive vs Negative colours values above zero as good and the rest as bad.

Keyboard

KeyWhereWhat it does
Tab, Shift + TabTableMoves between the column headers, each cell’s copy button and the page buttons.
Enter or SpaceColumn headerSorts ascending, then descending, then clears the sort.
Enter or SpacePage buttonGoes to the first, previous, next or last page.
Enter or SpaceCopy button in a cellCopies 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.