# Table usage guidelines

> Discover Cimpress UI's table component.

Source: https://ui.cimpress.io/components/table/

Data tables allow users to view and manage data in an organized way.

### When to use

- To present structured, comparable data in an easy-to-view grid format.
- When users need to scan, sort, or analyze multiple data points efficiently.
- For datasets where features such as sorting, filtering, or pagination are beneficial.
- To display relationships between multiple columns and rows of information.

### When not to use

- When presenting only a small amount of data that can be shown as a list or card layout.
- When creating a browsing experience where the user may not know what they're looking for or are discovering new data. For this, consider using [cards](/components/card) instead.
- If the data benefits from progressive disclosure or is difficult to show in a row and column format. For this consider using [disclosures](/components/disclosure) instead.
- When displaying hierarchical data that fits better in a tree.

## Usage

```tsx
import {
  Table,
  TableBody,
  TableBodyCell,
  TableBodyRow,
  TableContainer,
  TableHeader,
  TableHeaderCell,
  TableHeaderRow,
} from '@cimpress-ui/react';

const movies = [
  { title: 'The Shawshank Redemption', releaseYear: 1994, rating: 9.3 },
  { title: 'The Godfather', releaseYear: 1972, rating: 9.2 },
  { title: 'The Godfather: Part II', releaseYear: 1974, rating: 9.0 },
  { title: 'The Dark Knight', releaseYear: 2008, rating: 9.0 },
  { title: '12 Angry Men', releaseYear: 1957, rating: 8.9 },
  { title: "Schindler's List", releaseYear: 1993, rating: 8.9 },
  { title: 'The Lord of the Rings: The Return of the King', releaseYear: 2003, rating: 8.9 },
  { title: 'Pulp Fiction', releaseYear: 1994, rating: 8.9 },
  { title: 'The Lord of the Rings: The Fellowship of the Ring', releaseYear: 2001, rating: 8.8 },
  { title: 'Forrest Gump', releaseYear: 1994, rating: 8.8 },
];

export default function Demo() {
  return (
    <TableContainer>
      <Table aria-label="Movies">
        <TableHeader>
          <TableHeaderRow>
            <TableHeaderCell columnKey="title">Title</TableHeaderCell>
            <TableHeaderCell columnKey="release-year" columnContentAlignment="end">
              Release year
            </TableHeaderCell>
            <TableHeaderCell columnKey="rating" columnContentAlignment="end">
              Rating
            </TableHeaderCell>
          </TableHeaderRow>
        </TableHeader>
        <TableBody>
          {movies.map((movie) => (
            <TableBodyRow key={movie.title}>
              <TableBodyCell columnKey="title">{movie.title}</TableBodyCell>
              <TableBodyCell columnKey="release-year">{movie.releaseYear}</TableBodyCell>
              <TableBodyCell columnKey="rating">
                <span aria-hidden>⭐️ </span>
                {movie.rating.toFixed(1)}
              </TableBodyCell>
            </TableBodyRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
```

## Formatting and layout

### Placement

Ensure tables are placed with enough space that the table and the UI aren't crowded. If the table has a large number of rows or columns, it should be the focal point of the UI and should not be crammed into a space it does not fit. For tables with many columns or an unpredictable number of columns, horizontal scrolling can be used to manage space on the page.

### Cell content

Cells can contain either plain text, text links, or other components. Each cell should only contain one type of content - that is, all content within a cell should be either interactive or non-interactive, and never a mix of both.

Cells that use other components like badges and actions should use the small size for that component.

#### Cell alignment

Cell content type should always be aligned consistently:

- Left-align text content
- Right-align numerical data
- Center-align status indicators, badges, and action buttons

**Do:**

```tsx
import { Table, useTableEngine } from '@cimpress-ui/tanstack-table-react';
import { getCoreRowModel } from '@cimpress-ui/tanstack-table-react/base';
import { baseColumns, products, type Product } from './data.noexample.js';

export default function Demo() {
  const engine = useTableEngine<Product>({
    columns: baseColumns,
    data: products,
    getCoreRowModel: getCoreRowModel(),
  });

  return <Table engine={engine} aria-label="Example table showcasing the alignment of cell content" />;
}
```

#### Row actions

Rows can contain actions that affect only that single row. The actions column should always be the right-most column in the table, and the actions in the column should be consistent across each row. There are several ways of achieving actions in rows:

- **Single action**: if there is only one action the user can take, use a single button.
- **2-3 actions**: if there are 2-3 actions, icon buttons can be used to display all the actions together. This should only be used for actions that have clear and common icons like "edit", "delete", and "view".
- **3+ actions and complex actions**: a menu is used if there are more than three actions, or if the actions do not have an obvious and common icon and would be more clear when written out with a label.

**Do:**

```tsx
import { Button } from '@cimpress-ui/react';
import { Table, useTableEngine } from '@cimpress-ui/tanstack-table-react';
import { getCoreRowModel } from '@cimpress-ui/tanstack-table-react/base';
import { baseColumns, columnHelper, products, type Product } from './data.noexample.js';

const columns = [
  ...baseColumns,
  columnHelper.display({
    id: 'action',
    header: 'Single button',
    cell: () => <Button size="small">Test product</Button>,
    contentAlignment: 'center',
  }),
];

export default function Demo() {
  const engine = useTableEngine<Product>({
    columns,
    data: products,
    getCoreRowModel: getCoreRowModel(),
  });

  return <Table engine={engine} aria-label="Example table showcasing a single row action" />;
}
```

**Do:**

```tsx
import { IconButton, Stack } from '@cimpress-ui/react';
import { IconAdd, IconSubtract } from '@cimpress-ui/react/icons';
import { Table, useTableEngine } from '@cimpress-ui/tanstack-table-react';
import { getCoreRowModel } from '@cimpress-ui/tanstack-table-react/base';
import { baseColumns, columnHelper, products, type Product } from './data.noexample.js';

const columns = [
  ...baseColumns,
  columnHelper.display({
    id: 'action',
    header: 'Icon buttons',
    cell: () => (
      <Stack gap={8} direction="horizontal" justify="center">
        <IconButton size="small" variant="tertiary" icon={<IconAdd />} aria-label="Add product" />
        <IconButton size="small" variant="tertiary" icon={<IconSubtract />} aria-label="Delete product" />
      </Stack>
    ),
    contentAlignment: 'center',
  }),
];

export default function Demo() {
  const engine = useTableEngine<Product>({
    columns,
    data: products,
    getCoreRowModel: getCoreRowModel(),
  });

  return <Table engine={engine} aria-label="Example table showcasing two row actions" />;
}
```

**Do:**

```tsx
import { IconButton, Menu, MenuItem, MenuRoot } from '@cimpress-ui/react';
import { IconMenuMoreHorizontal } from '@cimpress-ui/react/icons';
import { Table, useTableEngine } from '@cimpress-ui/tanstack-table-react';
import { getCoreRowModel } from '@cimpress-ui/tanstack-table-react/base';
import { baseColumns, columnHelper, products, type Product } from './data.noexample.js';

const columns = [
  ...baseColumns,
  columnHelper.display({
    id: 'action',
    header: 'Menu',
    cell: () => (
      <MenuRoot>
        <IconButton size="small" variant="tertiary" icon={<IconMenuMoreHorizontal />} aria-label="Row actions" />
        <Menu>
          <MenuItem>Add product</MenuItem>
          <MenuItem>Test product</MenuItem>
          <MenuItem>Delete product</MenuItem>
        </Menu>
      </MenuRoot>
    ),
    contentAlignment: 'center',
  }),
];

export default function Demo() {
  const engine = useTableEngine<Product>({
    columns,
    data: products,
    getCoreRowModel: getCoreRowModel(),
  });

  return <Table engine={engine} aria-label="Example table showcasing a menu of row actions" />;
}
```

#### Column sorting

Column headers in the table component have sort functionality built in. Use this for sorting tables by columns, and avoid adding additional sort actions outside of the table.

### Pagination alignment

Pagination is useful to keep tables easily readable for users when there are large data sets. Generally tables should show 10 rows per page and provide pagination so that users can easily understand the data in the table. If a table contains predictable and static data, more than 10 rows can be shown, but if the number of rows is unpredictable or the table will become excessively long, pagination should be used. For large data sets it can be helpful to allow users to select how many rows per page they would like to see. For this, use a menu with selectable items, and left-align it with the bottom of the table.

**Do:**

```tsx
import {
  Button,
  Menu,
  MenuItem,
  MenuRoot,
  Pagination,
  Stack,
  Table,
  TableBody,
  TableBodyCell,
  TableBodyRow,
  TableContainer,
  TableHeader,
  TableHeaderCell,
  TableHeaderRow,
} from '@cimpress-ui/react';
import { IconChevronDown } from '@cimpress-ui/react/icons';
import { useState } from 'react';

interface Album {
  title: string;
  releaseDate: string;
  label: string;
  chartPosition: number;
}

const labels = ['Interscope', 'Universal'];

const albums: Album[] = Array(1000)
  .fill(0)
  .map((_, i) => ({
    title: `Album #${i + 1}`,
    releaseDate: `July 8, ${1997 + i}`,
    label: labels[i % labels.length],
    chartPosition: 1000 - i,
  }));

export default function Demo() {
  const [currentPage, setCurrentPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  const firstDisplayedRowIdx = rowsPerPage * (currentPage - 1);

  return (
    <Stack gap={16}>
      <TableContainer>
        <Table id="album-table" aria-label="Albums" totalRowCount={albums.length + 1}>
          <TableHeader>
            <TableHeaderRow rowNumber={1}>
              <TableHeaderCell columnKey="title" columnWidth="40%" columnContentAlignment="start">
                Title
              </TableHeaderCell>
              <TableHeaderCell columnKey="release-date" columnWidth="20%" columnContentAlignment="end">
                Release date
              </TableHeaderCell>
              <TableHeaderCell columnKey="label" columnWidth="20%" columnContentAlignment="start">
                Label
              </TableHeaderCell>
              <TableHeaderCell columnKey="chart-position" columnWidth="20%" columnContentAlignment="end">
                Chart position
              </TableHeaderCell>
            </TableHeaderRow>
          </TableHeader>

          <TableBody>
            {albums.slice(firstDisplayedRowIdx, firstDisplayedRowIdx + rowsPerPage).map((row, index) => (
              <TableBodyRow key={row.title} rowNumber={firstDisplayedRowIdx + index + 2}>
                <TableBodyCell columnKey="title">{row.title}</TableBodyCell>
                <TableBodyCell columnKey="release-date">{row.releaseDate}</TableBodyCell>
                <TableBodyCell columnKey="label">{row.label}</TableBodyCell>
                <TableBodyCell columnKey="chart-position">{row.chartPosition}</TableBodyCell>
              </TableBodyRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      <Stack gap={16} direction="horizontal" justify="space-between" align="start">
        <MenuRoot>
          <Button iconEnd={<IconChevronDown />}>Per page: {rowsPerPage}</Button>
          <Menu
            selectionMode="single"
            selectedKeys={[rowsPerPage]}
            onSelectionChange={(keys) => {
              if (keys === 'all') return;

              const selectedKey = keys.values().next().value;
              setCurrentPage(1);
              setRowsPerPage(selectedKey as number);
            }}
          >
            <MenuItem id={10}>10</MenuItem>
            <MenuItem id={25}>25</MenuItem>
            <MenuItem id={50}>50</MenuItem>
            <MenuItem id={100}>100</MenuItem>
          </Menu>
        </MenuRoot>

        <Pagination
          aria-label="Table pagination"
          currentPage={currentPage}
          pageCount={Math.ceil(albums.length / rowsPerPage)}
          paginatedElementId="album-table"
          onPageChange={setCurrentPage}
        />
      </Stack>
    </Stack>
  );
}
```

#### Infinite scrolling

Infinite scrolling should not be used for tables. Using pagination gives users better control when they are navigating the data and it gives them a more comprehensive view of the data set so they are not endlessly scrolling.

### Filter alignment

For simple table filtering and searching, actions should be placed above the table. These filters should be directly connected to the table columns and provide simple selections on the most important columns.

Tables with many filters or complex filters should use a more advanced filtering experience. This is often achieved in a sidebar or a drawer.

### Batch and table action alignment

Batch actions or other table-level actions (like creating a new row) should be placed above the table. At most only one primary button should be used for table-level actions.

## Content writing

**Headers**

- Use clear, concise labels for each column and limit the header length to no more than a few words (for example "Status" instead of "Current status of order").
- Use sentence case for headers. Don't use all caps. See [capitalization](/foundations/content-writing#capitalization).
- Headers can have an icon either before or after the text. Icons should only be used where they provide additional and new context or information rather than as a supplemental representation of the written header text.

**Cells**

- Keep cell content as concise as possible.
- Cells should only contain one type of content. That is, all content within a cell should be either interactive or non-interactive, and never a mix of both.

## Behaviors

### Empty states

Empty tables should always display a title and a description explaining that there is no data to show, and what the user can do to fix the issue. There are a few reasons why a user may encounter an empty table but most commonly, they encounter this pattern because there is no data or because of user selections.

#### No data

If the table is empty because there is truly no data to show, always explain why there isn't any data. If the data is user-generated, provide a call-to-action to create or add new data.

**Do:**

```tsx
import { Button } from '@cimpress-ui/react';
import { Table, useTableEngine } from '@cimpress-ui/tanstack-table-react';
import { getCoreRowModel } from '@cimpress-ui/tanstack-table-react/base';
import { baseColumns, type Product } from './data.noexample.js';

export default function Demo() {
  const engine = useTableEngine<Product>({
    columns: baseColumns,
    data: [],
    getCoreRowModel: getCoreRowModel(),
    cimpressUi: {
      emptyState: {
        title: 'No products yet',
        description: 'Your products will show up here. Create your first product to get started.',
        action: <Button size="small">Create product</Button>,
      },
    },
  });

  return <Table engine={engine} aria-label="Example table showcasing an empty state caused by no data" />;
}
```

#### User selections

Sometimes when searching, filtering, or making other selections, there might not be any data that matches the user's parameters. When this happens, an empty state should be shown to indicate that their parameters are too restrictive.

**Do:**

```tsx
import { Button } from '@cimpress-ui/react';
import { Table, useTableEngine } from '@cimpress-ui/tanstack-table-react';
import { getCoreRowModel } from '@cimpress-ui/tanstack-table-react/base';
import { baseColumns, type Product } from './data.noexample.js';

export default function Demo() {
  const engine = useTableEngine<Product>({
    columns: baseColumns,
    data: [],
    getCoreRowModel: getCoreRowModel(),
    cimpressUi: {
      emptyState: {
        title: 'No products matched your filters',
        description: 'Try adjusting or clearing your filters to find products.',
        action: <Button size="small">Clear filters</Button>,
      },
    },
  });

  return <Table engine={engine} aria-label="Example table showcasing an empty state caused by user selections" />;
}
```

#### Scrolling

The table becomes scrollable when its rows/columns take up more space than is available within the layout. When scrolling the table, the header remains visible at all times. Additionally, a gradient indicator is shown whenever the table can be scrolled in a specific direction.

```tsx
import {
  Table,
  TableBody,
  TableBodyCell,
  TableBodyRow,
  TableContainer,
  TableHeader,
  TableHeaderCell,
  TableHeaderRow,
} from '@cimpress-ui/react';

const movies = [
  { title: 'The Shawshank Redemption', releaseYear: 1994, rating: 9.3 },
  { title: 'The Godfather', releaseYear: 1972, rating: 9.2 },
  { title: 'The Godfather: Part II', releaseYear: 1974, rating: 9.0 },
  { title: 'The Dark Knight', releaseYear: 2008, rating: 9.0 },
  { title: '12 Angry Men', releaseYear: 1957, rating: 8.9 },
  { title: "Schindler's List", releaseYear: 1993, rating: 8.9 },
  { title: 'The Lord of the Rings: The Return of the King', releaseYear: 2003, rating: 8.9 },
  { title: 'Pulp Fiction', releaseYear: 1994, rating: 8.9 },
  { title: 'The Lord of the Rings: The Fellowship of the Ring', releaseYear: 2001, rating: 8.8 },
  { title: 'Forrest Gump', releaseYear: 1994, rating: 8.8 },
];

export default function Demo() {
  return (
    <div style={{ display: 'flex', width: 400, height: 300 }}>
      <TableContainer>
        <Table aria-label="Movies" UNSAFE_style={{ width: '200%' }}>
          <TableHeader>
            <TableHeaderRow>
              <TableHeaderCell columnKey="title">Title</TableHeaderCell>
              <TableHeaderCell columnKey="release-year" columnContentAlignment="end">
                Release year
              </TableHeaderCell>
              <TableHeaderCell columnKey="rating" columnContentAlignment="end">
                Rating
              </TableHeaderCell>
            </TableHeaderRow>
          </TableHeader>
          <TableBody>
            {movies.map((movie) => (
              <TableBodyRow key={movie.title}>
                <TableBodyCell columnKey="title">{movie.title}</TableBodyCell>
                <TableBodyCell columnKey="release-year">{movie.releaseYear}</TableBodyCell>
                <TableBodyCell columnKey="rating">
                  <span aria-hidden>⭐️ </span>
                  {movie.rating.toFixed(1)}
                </TableBodyCell>
              </TableBodyRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}
```
