App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
import React, { useEffect, useState } from "react"; import ReactPaginate from "react-paginate"; import Table from "react-bootstrap/Table"; import "bootstrap/dist/css/bootstrap.min.css"; function App() { const [posts, setPosts] = useState([]); const [currentPage, setCurrentPage] = useState(0); const postsPerPage = 10; const offset = currentPage * postsPerPage; const currentPosts = posts.slice(offset, offset + postsPerPage); const pageCount = Math.ceil(posts.length / postsPerPage); // load the data useEffect(() => { const fetchPosts = async () => { try { const response = await fetch( "https://jsonplaceholder.typicode.com/posts" ); const data = await response.json(); console.log(data); setPosts(data); } catch (error) { console.log(error); } }; fetchPosts(); }, []); // when your page changes const handlePageClick = ({ selected }) => { setCurrentPage(selected); }; return ( <div className="container mt-5"> <h2 className="mb-4">Posts Table</h2> <Table striped bordered hover> <thead> <th>ID</th> <th>Title</th> <th>Body</th> </thead> <tbody> {currentPosts.map((post) => ( <tr key={post.id}> <td>{post.id}</td> <td>{post.title}</td> <td>{post.body}</td> </tr> ))} </tbody> </Table> <ReactPaginate previousLabel={"Previous"} nextLabel={"Next"} breakLabel={"..."} pageCount={pageCount} marginPagesDisplayed={2} pageRangeDisplayed={5} onPageChange={handlePageClick} containerClassName={"pagination justify-content-center"} pageClassName={"page-item"} pageLinkClassName={"page-link"} previousClassName={"page-item"} previousLinkClassName={"page-link"} nextClassName={"page-item"} nextLinkClassName={"page-link"} breakClassName={"page-item"} breakLinkClassName={"page-link"} activeClassName={"active"} /> </div> ); } export default App; |