Build a pagination component for a list of items.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
import React, { useState } from 'react';
function Pagination({ totalItems, itemsPerPage, onPageChange }) {
const totalPages = Math.ceil(totalItems / itemsPerPage);
return (
<div>
{Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
<button key={page} onClick={() => onPageChange(page)}>
{page}
</button>
))}
</div>
);
}
function PaginatedList() {
const allItems = Array.from({ length: 50 }, (_, i) => `Item ${i + 1}`);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
const currentItems = allItems.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);
return (
<div>
<ul>
{currentItems.map(item => <li key={item}>{item}</li>)}
</ul>
<Pagination
totalItems={allItems.length}
itemsPerPage={itemsPerPage}
onPageChange={setCurrentPage}
/>
</div>
);
}
export default PaginatedList;