Start learning free

LESSON 156 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Sortable Data Table

Practice

A data table is a classic interview task: show rows, sort them when a column header is clicked, and split them into pages. The Corner Shop's 8 products are in src/products.js. The table shows 3 at a time, sorted by name.

JavaScript's sort takes a compare function. It gets two items and returns a negative number when the first goes first, a positive number when the second goes first, and 0 for a tie. sort changes the array it is called on, so you sort a copy. Turn the sign around and the order turns around:

const words = ["pear", "fig", "banana"];
const longestFirst = [...words];
longestFirst.sort((a, b) => b.length - a.length);
// ["banana", "pear", "fig"]

Clicking a header sorts by that column, A to Z or low to high. Clicking the same header again flips the order. The sorted column's header gets aria-sort, "ascending" or "descending", so a screen reader can say it. A new sort goes back to page 1. Previous is disabled on page 1, and Next is disabled on the last page.

The check clicks Next, Next, Previous, then Price twice. Part of what it must see:

> open the page
    row: Gift card | $50 | 999
    row: Lamp | $29 | 1
    row: Mug | $12 | 10
    button: Previous (disabled)
    text: Page 1 of 3
    button: Next
> click "Price"
    row: Pen | $2 | 120
    row: Notebook | $7 | 0
    row: Stapler | $9 | 15
> click "Price"
    row: Gift card | $50 | 999
    row: Lamp | $29 | 1
    row: Teapot | $22 | 4
> the aria-sort of each column header
  Name: (none)
  Price: descending
  Stock: (none)

Your task: in src/App.jsx, the page math (pageCount, start, rows) and the header buttons are already there. Sort the copy by sortKey and direction, make sortBy pick the column and flip the order, set aria-sort, add the Previous and Next buttons and the page text, and go back to page 1 after a sort.


Assignment
Follow the Coding Tutorial to sort the product table by any column, both ways, and page through it 3 rows at a time.


Hint
a[sortKey] reads the column the table is sorted by. For descending, return the opposite of what compare says. A button is turned off with disabled={…}.


STEP 1 OF 11
    Ctrl + Enter to check