Pagination is a crucial feature in modern web applications, enabling users to navigate through large datasets or content more efficiently. In this tutorial, we'll explore how to implement pagination in a React.js application.
To follow along, you should have a basic understanding of React.js and have Node.js installed on your machine.
First, Let's setup our React App:
npx create-react-app react-pagination-tutorial
cd react-pagination-tutorial
Step 1: Fetching data
For the sake of simplicity, we'll use the JSONPlaceholder
API to simulate fetching data. Open the src/App.js
file and replace its contents with the following code:
import "./styles.css";
import {useEffect, useState} from 'react';
export default function App() {
const [data, setData] = useState();
const [currentPage, setCurrentPage] = useState(1);
const [dataPerPage] = useState(5);
useEffect(() =>{
const fetchData = async () =>{
const data = await fetch('https://jsonplaceholder.typicode.com/posts')
const json = await data.json();
setData(json);
}
fetchData();
},[])
const changePageNo = (number) => setCurrentPage(number);
const lastIndex = currentPage * dataPerPage;
const firstIndex = lastIndex - dataPerPage;
const currentData = data?.slice(firstIndex,lastIndex);
return (
<div className="App">
{currentData && currentData.map((data) =>{
return <ul key={data.id}>
<li>{data.title}</li>
</ul>
})}
</div>
);
}
Code Explanation:
- We set
currentPage
state to keep track of the current page. -
dataPerPage
is the number of posts displayed per page (in this case, 5). - We calculate
lastIndex
andfirstIndex
to slice the data array based on the current page. -
currentData
contains the posts that will be displayed on the current page. - The
changePageNo
function is used to update thecurrentPage
state when the user clicks on a different page number.
Step 2: Creating the Pagination Component
Now let's create the Pagination component and pass all the data as props(Remember to import the Pagination Component):
return (
<div className="App">
{currentData && currentData.map((data) =>{
return <ul key={data.id}>
<li>{data.title}</li>
</ul>
})}
{/* Pagination Component */}
<Pagination
changePageNo={changePageNo}
data={data?.length}
dataPerPage={dataPerPage}
currentPage={currentPage}
/>
</div>
);
This is our Pagination.js file:
export default function Pagination({
changePageNo,
data,
dataPerPage,
currentPage
}) {
let numbers = [];
for (let i = 1; i <= Math.ceil(data/dataPerPage) ;i++){
numbers.push(i);
}
return <div>
{numbers && numbers.map((no) =>{
return <button key={no}
onClick={() =>{
changePageNo(no);
}}
>{no}</button>
})}
</div>;
}
Note that we are using a for
loop runs from 1 to Math.ceil(data/dataPerPage)
(inclusive). This loop calculates the total number of pages required to display all the data items based on the dataPerPage
prop.
Final step: Adding styles
Now let's write some simple CSS code to set an active and a normal state for our buttons:
.active{
background-color: black;
color: white;
}
.normal{
background-color: white;
color:black;
}
Now modify the Pagination.js file to something like this:
return <div>
{numbers && numbers.map((no) =>{
return <button key={no}
// Adding active and normal state
className={no === currentPage?"active":"normal"}
onClick={() =>{
changePageNo(no);
}}
>{no}</button>
})}
</div>;
The className
is set based on whether the current no matches the currentPage
prop. If they match, the className
will be set to active, indicating that the button represents the currently active page. Otherwise, it will be set to normal for non-active pages.
Conclusion
In this tutorial, we walked through creating a simple pagination component in React.js. By following the steps, you've learned how to fetch data, divide it into pages, and display the content with pagination. Feel free to customize the styling and explore other pagination libraries to enhance the user experience. If you need any help or have some suggestions, feel free to express them in the comments.
Happy coding!
Top comments (0)