Skip to main content

Implement React Pagination with React Hooks and React Paginate

Page 1

Implement React Pagination with React Hooks and React Paginate

www.bacancytechnology.com


We often end up having a web application with a large number of data to be displayed. And at that time, Pagination comes to the rescue for managing such a vast dataset. In this blogpost, we will build a small application to implement ReactJS pagination using React Hooks and a package named React Paginate. Without further ado, let’s start coding! Here is the source code for React pagination example -> Github Repository. You can clone the repository and play around with the code. Let’s have a look at how to make pagination in ReactJS.


How to Implement Pagination Using React Hooks and React Paginate?


Create and Navigate to your React pagination project; npx create-react-app react-pagination cd react-pagination

Here’s How to Install Axios and React Paginate Based on your package manager, install Axios and React Paginate.


For yarn, run this command-

yarn add axios react-paginate

For npm, run this command-

npm install axios react-paginate


Now, open App.js and make the necessary changes.

Import React Hooks, React Paginate, and Axios iimport React, { useState, useEffect } from 'react' iimport axios from 'axios' iimport ReactPaginate from 'react-paginate';


Initializing React Hooks

const [postsPerPage] = useState(5); const [offset, setOffset] = useState(1); const [posts, setAllPosts] = useState([]); const [pageCount, setPageCount] = useState(0)


Fetching Data Using Axios We will use a dummy API -> https://jsonplaceholder.typicode.com/posts to fetch the data and display it. getAllposts() will be an async function that will return a response containing 100 posts. In getPostData(), we will manipulate data according to the HTML structure that needs to be displayed.


const getPostData = (data) => { return ( data.map(post => <div className="container" key={post.id}> <p>User ID: {post.id}</p> <p>Title: {post.title}</p> </div>) ) } const getAllPosts = async () => { const res = await axios.get(`https://jsonplaceholder.typicode.c om/posts`) const data = res.data; const slice = data.slice(offset - 1 , offset - 1 + postsPerPage) // For displaying Data const postData = getPostData(slice) // Using Hooks to set value setAllPosts(postData)


setPageCount(Math.ceil(data.length / postsPerPage)) } const handlePageClick = (e) => { const selectedPage = e.selected; setOffset(selectedPage + 1) };


Here we will fetch data using Axios and then store the response in the variable named data. The motive behind the JavaScript function – slice, is to slice our data, i.e., 100array.slice(0, 0+5)). Further, we will loop the data using a map function, return the HTML structure and store it in the variable named postData. Then, update the state with postData using React hook setAllPosts. This was related to updating our data. Now, for updating the pageCount we will use (Math.ceil(data.length / postsPerPage)) and further store it using setPageCount hook.


Call getAllPosts() from React hooks – useEffect() useEffect(() => {getAllPosts()}, [offset])

Create a method for handling the page click const handlePageClick = (event) => { const selectedPage = event.selected; setOffset(selectedPage + 1) };


Now you just need to return your posts and implement the ReactPaginate tag using some of its props. We will call handlePageClick() using onPageChange props, so whenever we click on next or previous, the method handlePageClick() will be called.


return ( <div className="main-app"> {/* Display all the posts */} {posts} {/* Using React Paginate */} <ReactPaginate previousLabel={"previous"} nextLabel={"next"} breakLabel={"..."} breakClassName={"break-me"} pageCount={pageCount} onPageChange={handlePageClick} containerClassName={"pagination"} subContainerClassName={"pages pagination"} activeClassName={"active"} /> </div> );


After implementing the above code snippets, your App.js would look something like this-


App.js hosted with ❤ by GitHub view raw


In case you want CSS code for App.css; it’s here-


App.css hosted with ❤ by GitHub view raw


After the coding part is done, as shown above, ReactJS pagination example would look something like this –

Video URL: https://www.bacancytechnology.com/blog/wpcontent/uploads/2021/03/Reactpagination.mp4?_=1


I hope this comprehensive tutorial of ReactJS pagination using React hooks and React paginate has helped you the way you’ve expected. If you are looking for a helping hand to implement pagination using React hooks and React paginate then Hire ReactJS developer to leverage the expertise.


Thank You

www.bacancytechnology.com


Turn static files into dynamic content formats.

Create a flipbook
Implement React Pagination with React Hooks and React Paginate by Bacancy Technology - Issuu