Skip to content
Recipes/Sortable table

Sortable table

A table whose headers sort the list in the URL. A click sorts by the column; another click flips it; a shift-click adds it to the sorts already applied.

src/articles/sort-header.tsx
import { getAriaSort } from '@qubeejs/core';
import type { QubeeListHandle } from '@qubeejs/react';
import type { ReactNode } from 'react';
import type { articleList } from './article-list';
type SortHeaderProps = {
children: ReactNode;
field: 'publishedAt' | 'title';
list: QubeeListHandle<typeof articleList>;
};
/** The arrow for the direction a column is sorted in, if it is the primary sort. */
const ARROWS = { ascending: ' ▲', descending: ' ▼', none: '' } as const;
/**
* A column header that sorts the list by its field: a click sorts ascending,
* the next one flips it; a shift-click adds the field to the sorts in place.
*/
export function SortHeader({ children, field, list }: SortHeaderProps) {
const direction = getAriaSort(list.state.sort, field);
return (
<th aria-sort={direction} scope="col">
<button onClick={(event) => list.toggleSort(field, { multiple: event.shiftKey })} type="button">
{children}
<span aria-hidden="true">{ARROWS[direction]}</span>
</button>
</th>
);
}
src/articles/article-table.tsx
import type { QubeeListHandle } from '@qubeejs/react';
import type { Article, articleList } from './article-list';
import { SortHeader } from './sort-header';
type ArticleTableProps = {
articles: readonly Article[];
list: QubeeListHandle<typeof articleList>;
};
/** How the table prints a publication date. */
const DATE_FORMAT = new Intl.DateTimeFormat('en', { dateStyle: 'medium' });
/** The articles on this page, under headers that sort the list. */
export function ArticleTable({ articles, list }: ArticleTableProps) {
return (
<table>
<thead>
<tr>
<SortHeader field="title" list={list}>
Title
</SortHeader>
<SortHeader field="publishedAt" list={list}>
Published
</SortHeader>
</tr>
</thead>
<tbody>
{articles.map((article) => (
<tr key={article.id}>
<td>{article.title}</td>
<td>{DATE_FORMAT.format(new Date(article.publishedAt))}</td>
</tr>
))}
</tbody>
</table>
);
}
  • list.toggleSort(field) exists because articleList declares exactly one sortParam, and field is typed to 'publishedAt' | 'title' — the fields that param allows.
  • A plain click makes the field the only sort: flipped when it was the primary sort, ascending otherwise — even if a secondary sort named it. { multiple: true } (a shift-click) flips the field in place wherever it is, or appends it ascending, keeping the other sorts.
  • The sort lives in the URL — ?sort=title, or ?sort=-publishedAt,title after a shift-click — and changing it goes back to page 1.
  • getAriaSort gives the primary sort column its direction and every other column 'none'.
  • Headers stay <th aria-sort><button type="button">: the button is reachable from the keyboard and announced as a control.

In a whole page: Lists in the URL.