DEV Community

WDSEGA
WDSEGA

Posted on

Component Deep Dive #45: Sortable Data Table — Click-to-Sort Header and Frontend Pagination in One Shot

Component Deep Dive #45: Sortable Data Table — Click-to-Sort Header and Frontend Pagination in One Shot

HTML <table> natively lacks sorting, pagination, and sticky headers. A feature-complete data table requires sorting logic, pagination state, fixed headers, and column resizing — each its own minefield.

The sorting implementation distinguishes data types via data-type attribute: strings sort lexicographically, numbers use Number() conversion, and dates use new Date().getTime() for timestamp comparison. The sticky header uses pure CSS (position: sticky; top: 0), but requires border-collapse: separate to avoid border disappearing.

Pagination state resets to page 1 when sorting changes. The renderTable function chains sort -> slice -> render, keeping the data flow single-directional. Key pitfalls include border-collapse breaking sticky headers, large array sort performance (consider pre-sorted indexes or Web Workers), and pagination overflow when total pages exceed 20 (implement ellipsis pagination).

Extensions include draggable column widths via mouse handlers on th resize handles, row selection with Shift+click range select, and backend pagination replacing frontend sort/slice with API parameters.

Top comments (0)