Pagination With Ellipsis

MediumAlgorithmsComponentsReact25 mins

by Pratik Rai

Read the full write-up

Build a <Pagination currPage totalPage onPageClick /> component.

The first page, the last page, the current page and its immediate neighbours are always visible. Anywhere numbers are missing between two visible ones, show a single instead.

Requirements

  1. Always show page 1, the last page, the current page, and the pages either side of the current one.

  2. Collapse any run of missing numbers into one .

  3. Never show a page number below 1 or above totalPage, and never show a duplicate.

  4. Clicking a number calls onPageClick with it; the current page is styled with .page-current.

  5. The ellipsis is not clickable.

Notes

  • Expected output: currPage 1, totalPage 10 gives 1 2 … 10. currPage 5 gives 1 … 4 5 6 … 10. currPage 9 gives 1 … 8 9 10.

  • The control above the component lets you change totalPage, so try small values — 1, 2 and 3 pages are where naive versions break.

Hints

Loading editor…