Deviopath › Next.js

Data Table State in the URL

Hard · Search Params

Build a data table whose search, sorting and pagination all live in the URL: /?q=li&sort=name&dir=desc&page=2. Opening that URL must render exactly that state, so keep none of it in React state.

- Search: <input className="search"> shows q. Typing sets q with router.replace (an empty value removes it). Only rows whose name contains q (case-insensitive) are shown.

- Headers: <th data-col="name"> and <th data-col="age">, each containing a <button> (Name, Age). Clicking a header sorts by it ascending; clicking the sorted header again flips dir between asc and desc. Use router.push.

- Each <th> has aria-sort: ascending or descending on the sorted column, none otherwise. Ties keep their original order in both directions. Without a valid sort (name or age) the original order is used; any dir other than desc means ascending.

- Pagination: 3 rows per page with <button className="prev">Previous</button>, <span className="page-info">Page 2 of 3</span> and <button className="next">Next</button>; the buttons are disabled on the first / last page. There is always at least 1 page.

- page must be a whole number >= 1, otherwise page 1 is shown; a page past the end shows the last page. Page 1 is written as no page param.

- Changing the search or the sort removes page (back to page 1). All other params are kept.

- Each row is <tr><td>name</td><td>age</td></tr> inside <tbody>.

Next: fetch Cache with Stale-While-Revalidate