Live coding · 45 minutes
Data table: sort, filter, paginate
Build a data table in React in 45 minutes, with no table library. Use a local array of about 200 objects, for example users with a name, an email, an age and a city. The user can sort by a column, filter the rows with a text input, and move through pages. Start with rendering and sorting, then add the filter, then the pagination. Explain your decisions while you code, as in a live round.
Requirements
- The rows are in a real table element with a header row
- A click on a header sorts by that column; a second click reverses the order; the header shows the direction
- Numbers sort as numbers and text sorts as text, and the original array is not changed
- A text input filters the rows by a match in any column, ignoring upper and lower case
- Pagination with 10 rows per page: Previous, Next, the current page and the number of pages
- A change of filter or sort returns to page 1
- When no row matches, the table shows a message
What reviewers look for
- The right order of steps: filter, then sort, then take the page
- The visible rows are derived during render (with useMemo if needed); only sort, filter text and page are state
- No mutation: the sort runs on a copy, because the array sort method changes the array in place
- A correct compare function for numbers, and localeCompare for text
- Edge cases: the last page after a filter, zero rows, a page number that no longer exists
- Semantic markup: th elements, a button in each sortable header, and aria-sort
Check before you hand it in
- Each column sorts in both directions, and age sorts as a number: 9 comes before 10
- Typing in the filter reduces the rows, ignores upper and lower case, and works together with the sort
- Previous and Next work and are disabled at the ends, and the number of pages follows the filter
- A new filter or sort returns to page 1, and I never see an empty page while rows exist
- My state holds only the sort, the filter text and the page; the visible rows are computed, and the source array is not changed
- I explained each decision aloud, including the order: filter, sort, then page
- Sorting, filtering and pagination worked together within 45 minutes
If there is time
- Make the columns a prop, with generics, so the table works for any row type
- Add a select for the page size
- Keep sort, filter and page in the URL
- Sort by a second column when two values are equal