diff --git a/src/App.tsx b/src/App.tsx index 189a990c8..3716416d7 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,5 @@ import React from 'react'; +import { Pagination } from './components/Pagination'; import './App.css'; import { getNumbers } from './utils'; @@ -6,24 +7,36 @@ import { getNumbers } from './utils'; const items = getNumbers(1, 42).map(n => `Item ${n}`); export const App: React.FC = () => { + const [currentPage, setCurrentPage] = React.useState(1); + const [perPage, setPerPage] = React.useState(5); + + const startItem = (currentPage - 1) * perPage + 1; + const endItem = Math.min(startItem + perPage - 1, items.length); + return (

Items with Pagination

- Page 1 (items 1 - 5 of 42) + Page {currentPage} (items {startItem} - {endItem} of {items.length})

@@ -33,77 +46,22 @@ export const App: React.FC = () => {
{/* Move this markup to Pagination */} - + { + setCurrentPage(page); + }} + />
); diff --git a/src/components/Pagination/Pagination.tsx b/src/components/Pagination/Pagination.tsx index e417a09fc..f0fdf2819 100644 --- a/src/components/Pagination/Pagination.tsx +++ b/src/components/Pagination/Pagination.tsx @@ -1 +1,79 @@ -export const Pagination = () => {}; +import React from 'react'; + +type Props = { + total: number; + perPage: number; + currentPage?: number; + onPageChange: (page: number) => void; +}; + +export const Pagination: React.FC = ({ + total, + perPage, + currentPage = 1, + onPageChange, +}) => { + const totalPages = Math.ceil(total / perPage); + + const handleClick = ( + page: number, + event: React.MouseEvent, + ) => { + event.preventDefault(); + + if (page < 1 || page > totalPages || page === currentPage) { + return; + } + + onPageChange(page); + }; + + return ( + + ); +};