Setting Up Simple Pagination with Purely React
A quick guide to setting up pagination using React only.
To Begin
Create your React application.
npx create react-app pagination-app
Navigate to the project directory.
cd pagination-app
Create a Pagination.js
component inside the src
folder.
import React from 'react';const Pagination = () => {
return (
<div> </div>
);
};export default Pagination;
Update App.js
to render the newly created Pagination
component.
import Pagination from './Pagination'function App() {
return (
<div className="App">
<Pagination />
</div>
);
}export default App;
Configuring the Pagination Component
Let’s set up some dummy data to display with our application.
We’ll also need to import the useState
hook.
import React, { useState } from 'react';
For this tutorial, we’ll be displaying three dog profiles per page. We also need to keep track of what page the user is currently on. We’ll use useState
to store this data.
const [currentPage, setCurrentPage] = useState(1);
const [dogsPerPage, setDogsPerPage] = useState(3);
Pagination Logic
We can use some simple math to determine the specific elements to display on every page.
// Calculates the index of the very last element to display on a specific page
const indexOfLastDog = currentPage * dogsPerPage;// With the index of the last element we can calculate the index of the first by subtracting 3 (max number of elements to display per page)
const indexOfFirstDog = indexOfLastDog - dogsPerPage;// We can determine the specific elements to display by utilizing the slice() method
const dogsToDisplay = mockData.slice(indexOfFirstDog, indexOfLastDog)
Displaying Our Data
Now that we can call dogsToDisplay
we can set up the display logic. Update the Pagination
component to return the following block of code.
Button Setup
Let’s create a couple of buttons to move between pages. We’ll need a Previous
button and a Next
button. When a button is clicked, it will increment our currentPage
value by plus 1 or minus 1.
We’ll need to create a function to handle the click event.
const handleClick = (value) => {
setCurrentPage(currentPage + value)
}
Next, we can move on to some button logic.
// If the current page is equal to 1 the button will be disabled
<button onClick={() => handleClick(-1)} disabled={currentPage === 1 && true} >Previous</button>// If the current page is equal to the last page the button will be disabled
<button onClick={() => handleClick(1)} disabled={currentPage === Math.ceil(mockData.length / dogsPerPage) && true}>Next</button>
Finally, we’ll create a simple page number display.
<p>Page {currentPage} of {Math.ceil(mockData.length / dogsPerPage)} results</p>
Putting It All Together
All together your Pagination Component should look like this.
Run yarn start
and view the final result!