diff --git a/README.md b/README.md index be8a8c6b6..5bb3d0db1 100644 --- a/README.md +++ b/README.md @@ -2,29 +2,29 @@ > Here is the [working version](https://mate-academy.github.io/react_pagination/) -You a given a list of items and markup for the `Pagination`. Implement the +You a given a list of items and markup for the `Pagination`. Implement the `Pagination` as a stateless component to show only the items for a current page. 1. The `Pagination` should be used with the next props: - ```jsx harmony - { ... }} - /> - ``` + ```jsx harmony + { ... }} + /> + ``` 1. Keep the HTML stucture `data-cy` attributes; 1. Show all the existing pages considering `total` and `perPage` 1. Current page should be highlighted with `li.active`; 1. `onPageChange` callback should be triggered only if page was changed; 1. The `App` should listen to the `onPageChange` and save a new page; 1. `«` and `»` links should open the prev and the next pages accordingly - - disable each of them if it is already the first or the last page (use `li.disabled` and `a[aria-disabled="true"]`) + - disable each of them if it is already the first or the last page (use `li.disabled` and `a[aria-disabled="true"]`) 1. Show the pagination info inside `data-cy="info"` in the next format `Page 1 (items 1 - 5 of 42)`; 1. Implement the ` - - - - + className="form-control" + value={perPage} + onChange={event => { + setPerPage(Number(event.target.value)); + setCurrentPage(1); + }} + > + + + + @@ -32,78 +50,19 @@ export const App: React.FC = () => { - {/* Move this markup to Pagination */} - + +
    -
  • Item 1
  • -
  • Item 2
  • -
  • Item 3
  • -
  • Item 4
  • -
  • Item 5
  • + {visibleItems.map(item => ( +
  • + {item} +
  • + ))}
); diff --git a/src/components/Pagination/Pagination.tsx b/src/components/Pagination/Pagination.tsx index e417a09fc..8f362bede 100644 --- a/src/components/Pagination/Pagination.tsx +++ b/src/components/Pagination/Pagination.tsx @@ -1 +1,92 @@ -export const Pagination = () => {}; +type Props = { + total: number; + perPage: number; + currentPage: number; + onPageChange: (page: number) => void; +}; + +const getNumbers = (from: number, to: number): number[] => { + const numbers = []; + + for (let i = from; i <= to; i++) { + numbers.push(i); + } + + return numbers; +}; + +export const Pagination: React.FC = ({ + total, + perPage, + currentPage, + onPageChange, +}) => { + const pagesCount = Math.ceil(total / perPage); + + const pages = getNumbers(1, pagesCount); + + const isFirstPage: boolean = currentPage === 1; + const isLastPage: boolean = currentPage === pagesCount; + + const handlePageChange = (page: number) => { + if (page !== currentPage) { + onPageChange(page); + } + }; + + return ( + + ); +};