01 logo

How to implement pagination using React Hooks

ReactJS Pagination using React Hooks. Learn about how to implement pagination with React hooks and React paginate to manage and display the vast data conveniently.

By BacancyPublished 3 years ago 3 min read
Like

Sometimes your web application contains a vast amount of data you can manage with Pagination that is used in some or the other way in every web application to display the data on multiple pages within one web page. Now we will learn how to implement pagination using react hooks by creating a small application.

Create react pagination project:

npx create-react-app react-pagination

cd react-pagination

Now you need to install Axios and run the following command

yarn add axios react-paginate

And after that install react paginate by running this command:

npm install axios react-paginate

After that you need to make the necessary changes in App.js

Import React Hooks, React Paginate, and Axios

import React, { useState, useEffect } from 'react'

import axios from 'axios'

import 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)

Now we need to fetch the data in Axios and for that we will manipulate the data and use a dummy data structure for displaying it.

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.com/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)

};

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 it is time to implement reactPaginate tag and so we will call handlePageClick() by using the props of onPageChange so that if we want to click on the next or previous button handlePageClick() function will do its work at any time.

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>

);

The result after the implementation will look something like this:

import React, { useState, useEffect } from 'react'

import axios from 'axios'

import ReactPaginate from 'react-paginate';

import './App.css'

function App() {

const [postsPerPage] = useState(5);

const [offset, setOffset] = useState(1);

const [posts, setAllPosts] = useState([]);

const [pageCount, setPageCount] = useState(0)

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.com/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 = (event) => {

const selectedPage = event.selected;

setOffset(selectedPage + 1)

};

useEffect(() => {

getAllPosts()

}, [offset]

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>

);

If you want CSS code for App.css

.main-app {

margin: 2% 10%;

border: 1px ridge #464141;

padding: 5%;

font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;

font-size: 20px;

color: #464141;

}

.container {

border-bottom: #fff 2px ridge;

}

.pagination {

margin-top: 45px;

margin-left: -40px;

display: flex;

list-style: none;

outline: none;

}

.pagination>.active>a {

background-color: #47ccde;

color: #fff;

}

.pagination>li>a {

border: 1px solid #47ccde;

padding: 5px 10px;

outline: none;

cursor: pointer;

}

.pagination>li>a, .pagination>li>span {

color: #47ccde;

background-color: azure;

}

export default App;

The result will look like this after the implementation of codes.

To conclude, I hope this comprehensive tutorial that shows the implementation of pagination using ReactJS and React hooks and React paginate would have helped you in any way possible.

how to
Like

About the Creator

Bacancy

A Leader in Agile and Lean Software Development

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2024 Creatd, Inc. All Rights Reserved.