Lesson 8 of 8

Pagination

Goal

Page number in state, slicing at render time

01

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.

02

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
  1. The first page shows only "Product 1" through "Product 5"
  2. The "Next" button moves on to the next five items
  3. The last page shows the three remaining items
  4. "Previous" is disabled on the first page and "Next" on the last
  5. The text shows the page number, like "Page 1 of 5"
  6. Rendering depends on state.page alone
03

Hints

0/3
Track lessons0 of 8 done

A UI is built from data, so here you learn to filter, sort and group that data without touching the DOM directly.

Intermediate level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

A UI is built from data, so here you learn to filter, sort and group that data without touching the DOM directly.

Intermediate level, 8 lessons, 2 hours in total.