Lesson 8 of 8
Pagination
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
Page number in state, slicing at render time
Explanation
A list with a thousand items isn't shown all at once but split into pages. You keep a single number in the state, the current page, and compute everything else from it when you render: where the slice starts, how many pages there are in total, and which button should be disabled.
The math takes two lines: start = (page - 1) * PER_PAGE, then items.slice(start, start + PER_PAGE). The slice method doesn't change the original and doesn't throw if you go past the end of the array, so the last, shorter page comes out right without any extra effort.
All the bugs live at the edges. If you count the pages with Math.floor, you lose the last partial page, because 23 items need Math.ceil(23 / 5), that is 5 pages, not 4. And if you leave the "Next" button enabled on the last page, it takes the user to an empty page.
Your task
Show five items from page state.page (numbering starts at 1), write the page number in #info in exactly the form "Page 1 of 5", disable #prev on the first page and #next on the last, and make both buttons change state.page and then re-render.
Checks
6 checks- The first page shows only "Product 1" through "Product 5"
- The "Next" button moves on to the next five items
- The last page shows the three remaining items
- "Previous" is disabled on the first page and "Next" on the last
- The text shows the page number, like "Page 1 of 5"
- Rendering depends on state.page alone