SlideShare a Scribd company logo
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?
npx create-react-app react-pagination
cd react-pagination
Create and Navigate to
your React pagination
project;
Here’s How to Install
Axios and React
Paginate
Based on your package manager, install
Axios and React Paginate.
yarn add axios react-paginate
For yarn, run this command-
For npm, run this command-
npm install axios react-paginate
iimport React, { useState, useEffect } from 'react'
iimport axios from 'axios'
iimport ReactPaginate from 'react-paginate';
Now, open App.js and make the necessary
changes.
Import React Hooks,
React Paginate, and Axios
const [postsPerPage] = useState(5);
const [offset, setOffset] = useState(1);
const [posts, setAllPosts] = useState([]);
const [pageCount, setPageCount] = useState(0)
Initializing React Hooks
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.
Fetching Data Using
Axios
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-
Implement react pagination with react hooks and react paginate
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/wp-
content/uploads/2021/03/React-
pagination.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
Ad

Recommended

Introduction to MongoDB
Introduction to MongoDB
Chun-Kai Wang
 
React / Redux Architectures
React / Redux Architectures
Vinícius Ribeiro
 
Redux Universal
Redux Universal
Nikolaus Graf
 
Firebase ng2 zurich
Firebase ng2 zurich
Christoffer Noring
 
Grails Simple Login
Grails Simple Login
moniguna
 
React & Redux
React & Redux
Federico Bond
 
React lecture
React lecture
Christoffer Noring
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
Binary Studio
 
React state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
Introduction to react and redux
Introduction to react and redux
Cuong Ho
 
React + Redux. Best practices
React + Redux. Best practices
Clickky
 
Better web apps with React and Redux
Better web apps with React and Redux
Ali Sa'o
 
React & redux
React & redux
Cédric Hartland
 
React + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Redux training
Redux training
dasersoft
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
DreamLab
 
React js
React js
Oswald Campesato
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
DreamLab
 
React.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
Remo Jansen
 
Learn react-js
Learn react-js
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
Grails Advanced
Grails Advanced
Saurabh Dixit
 
React JS and Redux
React JS and Redux
Glib Kechyn
 
ReactJS for Beginners
ReactJS for Beginners
Oswald Campesato
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
Introduction to React & Redux
Introduction to React & Redux
Boris Dinkevich
 
React Lifecycle and Reconciliation
React Lifecycle and Reconciliation
Zhihao Li
 
Better React state management with Redux
Better React state management with Redux
Maurice De Beijer [MVP]
 
reactJS
reactJS
Syam Santhosh
 
Integrating React.js with PHP projects
Integrating React.js with PHP projects
Ignacio Martín
 

More Related Content

What's hot (20)

React state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
Introduction to react and redux
Introduction to react and redux
Cuong Ho
 
React + Redux. Best practices
React + Redux. Best practices
Clickky
 
Better web apps with React and Redux
Better web apps with React and Redux
Ali Sa'o
 
React & redux
React & redux
Cédric Hartland
 
React + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Redux training
Redux training
dasersoft
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
DreamLab
 
React js
React js
Oswald Campesato
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
DreamLab
 
React.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
Remo Jansen
 
Learn react-js
Learn react-js
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
Grails Advanced
Grails Advanced
Saurabh Dixit
 
React JS and Redux
React JS and Redux
Glib Kechyn
 
ReactJS for Beginners
ReactJS for Beginners
Oswald Campesato
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
Introduction to React & Redux
Introduction to React & Redux
Boris Dinkevich
 
React Lifecycle and Reconciliation
React Lifecycle and Reconciliation
Zhihao Li
 
Better React state management with Redux
Better React state management with Redux
Maurice De Beijer [MVP]
 
React state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
Introduction to react and redux
Introduction to react and redux
Cuong Ho
 
React + Redux. Best practices
React + Redux. Best practices
Clickky
 
Better web apps with React and Redux
Better web apps with React and Redux
Ali Sa'o
 
React + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Redux training
Redux training
dasersoft
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
DreamLab
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
DreamLab
 
React.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
Remo Jansen
 
React JS and Redux
React JS and Redux
Glib Kechyn
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
Introduction to React & Redux
Introduction to React & Redux
Boris Dinkevich
 
React Lifecycle and Reconciliation
React Lifecycle and Reconciliation
Zhihao Li
 
Better React state management with Redux
Better React state management with Redux
Maurice De Beijer [MVP]
 

Similar to Implement react pagination with react hooks and react paginate (20)

reactJS
reactJS
Syam Santhosh
 
Integrating React.js with PHP projects
Integrating React.js with PHP projects
Ignacio Martín
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JSFestUA
 
react.pdf
react.pdf
yihunie2
 
0900 learning-react
0900 learning-react
RohitYadav696
 
2- Components.pdf
2- Components.pdf
jibreelkhan2
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS Introduction
Visual Engineering
 
GDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJS
Pratik Majumdar
 
Reactjs
Reactjs
Neha Sharma
 
ReactJs
ReactJs
Sahana Banerjee
 
React introduction
React introduction
Kashyap Parmar
 
React js
React js
Rajesh Kolla
 
Tokyo React.js #3: Missing Pages: ReactJS/Flux/GraphQL/RelayJS
Tokyo React.js #3: Missing Pages: ReactJS/Flux/GraphQL/RelayJS
Khor SoonHin
 
Getting Started with React v16
Getting Started with React v16
Benny Neugebauer
 
React new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
React API and Hooksfjhfhjfjhfhjfjfjhfjhf
React API and Hooksfjhfhjfjhfhjfjfjhfjhf
DharnaAhuja1
 
How to navigate programmatically using react router
How to navigate programmatically using react router
BOSC Tech Labs
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
Robert DeLuca
 
Tech Talk on ReactJS
Tech Talk on ReactJS
Atlogys Technical Consulting
 
Battle of React State Managers in frontend applications
Battle of React State Managers in frontend applications
Evangelia Mitsopoulou
 
Integrating React.js with PHP projects
Integrating React.js with PHP projects
Ignacio Martín
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JSFestUA
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS Introduction
Visual Engineering
 
GDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJS
Pratik Majumdar
 
Tokyo React.js #3: Missing Pages: ReactJS/Flux/GraphQL/RelayJS
Tokyo React.js #3: Missing Pages: ReactJS/Flux/GraphQL/RelayJS
Khor SoonHin
 
Getting Started with React v16
Getting Started with React v16
Benny Neugebauer
 
React new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
React API and Hooksfjhfhjfjhfhjfjfjhfjhf
React API and Hooksfjhfhjfjhfhjfjfjhfjhf
DharnaAhuja1
 
How to navigate programmatically using react router
How to navigate programmatically using react router
BOSC Tech Labs
 
Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
Robert DeLuca
 
Battle of React State Managers in frontend applications
Battle of React State Managers in frontend applications
Evangelia Mitsopoulou
 
Ad

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Ad

Recently uploaded (20)

Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 

Implement react pagination with react hooks and react paginate

  • 1. Implement React Pagination with React Hooks and React Paginate www.bacancytechnology.com
  • 2. 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.
  • 4. npx create-react-app react-pagination cd react-pagination Create and Navigate to your React pagination project; Here’s How to Install Axios and React Paginate Based on your package manager, install Axios and React Paginate.
  • 5. yarn add axios react-paginate For yarn, run this command- For npm, run this command- npm install axios react-paginate
  • 6. iimport React, { useState, useEffect } from 'react' iimport axios from 'axios' iimport ReactPaginate from 'react-paginate'; Now, open App.js and make the necessary changes. Import React Hooks, React Paginate, and Axios
  • 7. const [postsPerPage] = useState(5); const [offset, setOffset] = useState(1); const [posts, setAllPosts] = useState([]); const [pageCount, setPageCount] = useState(0) Initializing React Hooks
  • 8. 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. Fetching Data Using Axios
  • 9. 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)
  • 10. setPageCount(Math.ceil(data.length / postsPerPage)) } const handlePageClick = (e) => { const selectedPage = e.selected; setOffset(selectedPage + 1) };
  • 11. 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.
  • 12. 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) };
  • 13. 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.
  • 14. 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> );
  • 15. After implementing the above code snippets, your App.js would look something like this-
  • 17. App.js hosted with ❤ by GitHub view raw
  • 18. In case you want CSS code for App.css; it’s here-
  • 19. App.css hosted with ❤ by GitHub view raw
  • 20. After the coding part is done, as shown above, ReactJS pagination example would look something like this – Video URL: https://www.bacancytechnology.com/blog/wp- content/uploads/2021/03/React- pagination.mp4?_=1
  • 21. 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.