Pagination is an integral part of any modern web and mobile application. In this article, we will look at how to implement pagination into a table that shows weather data. We’ll be using react, node.js, the OpenWeatherMap API, as well as the react-paginate library itself.
In the tutorial, you will learn how to set up a server, make API requests, work with the state in react, work with the react pagination library. After successfully completing the react pagination tutorial, you will be able to implement pagination to your application.
Also in the second part of the article, we will describe several other ready-made solutions in order to work with react pagination.
What Is React Pagination?
Pagination is an important feature of any application where we need to handle large amounts of data into smaller chunks. As data grows it becomes essential for a developer to load data from API in chunks and show it in UI. It’s always a good practice to fetch data in a small & precise manner to improve the efficiency & performance of the application. Doing such things also reduces the latency & load time of a server.
In today’s world, most web applications cannot show all the data they need to show to their users at once and there are good reasons to not show all the data at once. So in that cases, developers use pagination – separate pages that render a piece of information. Thus react pagination is the pagination made with React.js technology.
Pagination is mostly implemented in coordination with the server-side code that allows the client applications to request the data in the form of groups. For example, a client could ask the server for a list of the first 20 products.
So pagination allows applications to provide a better user experience and allows users to navigate through the data easily. Pagination also helps to make requests to the server in parts, which subsequently has a beneficial effect on the speed of the web application.
Should I develop a component like react pagination myself? Not in our opinion unless you need very deep customization. Instead, you can better do more important things.
So let’s go to our tutorial.
Prerequisites
In order for you to successfully complete this guide, you need to be familiar with the following technologies:
- Basic javascript;
- You should be familiar with all the basic concepts of react;
- You should know what npm and webpack are;
- You must have node.js installed;
- You should know how to make simple requests to the server.
React Pagination Guide
Step 1 – Setting up a project
We’ll start by installing the boilerplate of react node.js application. For this, we will take a ready-made application – https://github.com/crsandeep/simple-react-full-stack. This is a simple full-stack React application with a Node.js and Express backend. Client-side code is written in React and the backend API is written using Express. We need the backend in order to make an API request and send data to the client.
For a quick start please type the following commands:
# Clone the repository
git clone https://github.com/crsandeep/simple-react-full-stack
# Go inside the directory
cd simple-react-full-stack
# Install dependencies
yarn (or npm install)
# Start development server
yarn dev (or npm run dev)
# Build for production
yarn build (or npm run build)
# Start production server
yarn start (or npm start)
If everything went well you will see something like this on your computer screen.
Now that you’ve started the application, development can begin. Notice that a browser tab has been opened for you with live reloading functionality to keep in sync with the application as you develop.
Also, before starting development, go to the project folder and familiarize yourself with the structure. The most important part for us is the /src folder, which contains 2 client folders – this is ours react application and the server folder, where the file for working with the index.js backend is located.
Step 2 – Server setup
In order to display data in our application, we will use the OpenWeatherMap API – https://openweathermap.org/current. We will use the section in the API documentation where we need to make a query to display data for several cities – Call current weather data for several cities. API returns the data from cities within the defined rectangle specified by the geographic coordinates. The request will look like this:
api.openweathermap.org/data/2.5/box/city?bbox={bbox}&appid={API key}
Next, we’ll start working with the index.js file in the server folder. Before starting work, we advise you to check if all libraries are installed – for example, express. We will also need the following libraries to work with the server:
- Cors – it allows you to enable CORS with several options;
- Axios – for API requests;
- Body-parser – allows you to parse incoming request bodies in a middleware before your handlers. In order to install these libraries, enter the following commands in the terminal one by one:
$ npm install cors
$ npm install axios
$ npm install body-parser
In index.js file
, we initialize these libraries:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const axios = require('axios');
Let’s declare an app variable to work with express:
const app = express();
Next, we directly make a request to the openweathermap API by entering the following code:
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('dist'));
app.get('/list', async (req, res) => {
try{
let result = await axios.get("http://api.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&appid=476787c5ccaf8b0949ff8b5bc02cdecc");
res.json(result.data);
} catch(e) {
console.log(e);
}
});
We use express.static(‘dist’)
to serve static files from the ‘dist’
directory.
And then we directly configure routing using the get method. We also use try-catch to not allow the server to crash if any error will arise.
After we have made requests to the API using app.listen, we start the server and specify the port that we will listen to. As a result, our file will look like this.
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('dist'));
app.get('/list', async (req, res) => {
try{
let result = await axios.get("http://api.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&appid=476787c5ccaf8b0949ff8b5bc02cdecc");
res.json(result.data);
} catch(e) {
console.log(e);
}
});
app.listen(process.env.PORT || 8080, () => console.log(`Listening on port ${process.env.PORT || 8080}!`));
Congratulations you just made a server to display data for our pagination application! Let’s work with the client part.
Step 3 – Developing client part of the application
In this part, we will start building the front-end part of the application. We will develop a table where we will display our data. To do this, go to the client folder and open the app.js file.
Note, we will use a ready-made library called react-paginate to create the pagination component – https://github.com/AdeleD/react-paginate. Please install this library for yourself by typing the command:
npm install react-paginate --save
Also, note that we will be doing pagination without lazy loading.
In our file, we import the following libraries:
import axios from 'axios';
import ReactPaginate from 'react-paginate';
And we will also start developing our table and pagination by initializing the initial state of our component, for this, we add the following code:
class App extends Component {
state = {
list: [],
perPage: 3,
page: 0,
pages: 0,
};
};
List
serves as an array that will store our data that will come from the server.
perPage
is the number of rows that we will show in our table.
Page
is the start page from which our table will begin.
Pages
are how many pages are in the table initially.
The next step is to make a request to our created server. To do this, we will add the following code to our file.
class App extends Component {
state = {
list: [],
perPage: 3,
page: 0,
pages: 0,
};
componentDidMount() {
this.makeHttpRequest();
}
makeHttpRequest = async() => {
let res = await axios.get('http://localhost:8080/list').catch(err => console.log(err));
const {perPage} = this.state;
const {list} = res.data;
this.setState({
list,
pages: Math.floor(list.length / perPage)
});
};
};
Please note that we determine how many pages will eventually be shown already at the request level by assigning the state pages by dividing the length of the list array by the number of items per page, recall that we have it equal to 3.
We also make API requests in componentDidMount
.
Next, let’s move on to the render method and finally do our table and pagination.
render() {
const {page, perPage, pages, list} = this.state;
let items = list.slice(page * perPage, (page + 1) * perPage);
let weathers = items.map(item => {
const { id, name, main } = item;
const { temp, humidity, pressure } = main;
const { speed } = item.wind;
return (
<tr key={id}>
<td>{name}</td>
<td>{temp}</td>
<td>{humidity}</td>
<td>{pressure}</td>
<td>{speed}</td>
</tr>
)
}) || '';
If we take a closer look at this code, we will see the following.
We created the items variable and used the slice method to split our array and only show 3 rows on each page.
We also created the weathers variable and used the map method to pull out the data and the list array we need, namely:
- City name;
- Temperature;
- Humidity;
- Atmosphere pressure;
- Wind speed.
Next, let’s make our table, which will finally show our data, for this we add the following block of code:
return (
<>
<table className='Table'>
<thead>
<tr>
<th>Name of the city</th>
<th>Temperature</th>
<th>Humidity</th>
<th>Pressure</th>
<th>Wind Speed</th>
</tr>
</thead>
<tbody>
{weathers}
</tbody>
</table>
</>
);
At this stage, if you are familiar with React, I hope there is no need to explain much, except that in the <tbody>
we put our variable weather, which will show our data. As a result, you should have the following table.
Let’s go to the main thing and add the Pagination component. Add it after the <table>
tag.
<ReactPaginate
previousLabel={'prev'}
nextLabel={'next'}
pageCount={pages}
onPageChange={this.handlePageClick}
containerClassName={'pagination'}
activeClassName={'active'}
/>
Here we saw that we need to add the handlePageClick
method. It will look like this:
handlePageClick = (event) => {
let page = event.selected;
this.setState({page})
}
That’s it – we have finished creating the pagination for our table. Let’s take a look at the whole App.js
file to get the big picture.
import React, { Component } from 'react';
import './app.css';
import axios from 'axios';
import ReactPaginate from 'react-paginate';
class App extends Component {
state = {
list: [],
perPage: 3,
page: 0,
pages: 0,
};
componentDidMount() {
this.makeHttpRequest();
}
makeHttpRequest = async() => {
let res = await axios.get('http://localhost:8080/list').catch(err => console.log(err));
const {perPage} = this.state;
const {list} = res.data;
this.setState({
list,
pages: Math.floor(list.length / perPage)
});
};
handlePageClick = (event) => {
let page = event.selected;
this.setState({page})
}
render() {
const {page, perPage, pages, list} = this.state;
let items = list.slice(page * perPage, (page + 1) * perPage);
let weathers = items.map(item => {
const { id, name, main } = item;
const { temp, humidity, pressure } = main;
const { speed } = item.wind;
return (
<tr key={id}>
<td>{name}</td>
<td>{temp}</td>
<td>{humidity}</td>
<td>{pressure}</td>
<td>{speed}</td>
</tr>
)
}) || '';
return (
<>
<table className='Table'>
<thead>
<tr>
<th>Name of the city</th>
<th>Temperature</th>
<th>Humidity</th>
<th>Pressure</th>
<th>Wind Speed</th>
</tr>
</thead>
<tbody>
{weathers}
</tbody>
</table>
<ReactPaginate
previousLabel={'prev'}
nextLabel={'next'}
pageCount={pages}
onPageChange={this.handlePageClick}
containerClassName={'pagination'}
activeClassName={'active'}
/>
</>
);
}
}
export default App;
If you did everything correctly, then the following result should come out (here we have already styled the table right away, we will show how to do this in the next step).
Step 4 – custom styles
In this step, we will add styles to our project. This step can be done a little earlier, depending on what kind you prefer to work with. We’ll be changing the styles fairly straightforwardly. To do this, find the App.css
file in the /src
folder of your project and add the following styles to make the table look like in the screenshot:
.Table {
border-spacing: 20px;
border: 1px solid #6c7ac9;
border-radius: 5px;
margin-top: 50px;
}
body {
margin: 0;
font-family: sans-serif;
color: #6c7ac9;
}
#root {
display: flex;
align-items: center;
flex-direction: column;
}
.pagination {
display: flex;
justify-content: space-between;
list-style: none;
margin-top: 20px;
padding: 0;
}
.pagination a {
cursor: default;
padding: 10px;
border-radius: 5px;
border: 1px solid #6c7ac9;
color: #6c7ac9;
margin-left: 10px;
}
.pagination li:not(.disabled) a:hover {
background-color: bisque;
cursor: pointer;
}
.pagination li a {
font-weight: bold;
}
.pagination li.active a {
color: #fff;
background: #6c7ac9;
}
.pagination li.disabled a {
pointer-events: none;
color: rgb(198, 197, 202);
border: 1px solid rgb(198, 197, 202);
}
Congratulations, you’ve now completed building your own React project with pagination. At the end of the article, we will post a link to GitHub, where you can download the project and install it for yourself.
Best React Pagination Example
Material-Ui Pagination component
Material UI is a component library for React teeming with powerful components that you should be using in your projects. If you’re just looking to create a good-looking app, Material UI can provide you with solid pre-styled components that will get the job done.
For enabling pagination using Material-UI, you need to import Pagination from '@material-ui/lab/Pagination'
and use <Pagination />
component.
The library provides several types of design of pagination:
- Basic pagination;
- Outlined pagination;
- Rounded pagination.
You can also set pagination size and range. Additionally, you can add buttons and use Table pagination.
React paginate
React paginate is one of the most popular pagination components to use while developing the tables or other pages where you need pagination.
The library is easy to install and use. It also has good options to deeply customize it. There are more than 25 options on how you can customize your pagination component using React paginate library.
React-bootstrap pagination component
React-bootstrap is a very useful library that replaces jQuery code in Bootstrap. Each component is built with React. React-bootstrap gives all the components that you have in the original Bootstrap (alerts, buttons, tables), so you can use them without pain.
React-bootstrap gives you a full set of options for pagination setup – it has already built <Pagination />
components that you can customize for your needs. It also has a basic API for set upping a size of pagination and styles.
Pagination React Component
React Component pagination is a part of ant.design foundation library. It gives you a simple pagination component for your existing react application. The library can be installed in a couple of commands and it has a wide variety of API options. It also has several styles of pagination:
- Basic;
- Jumper;
- Sized;
- Locate;
- Fewer pages and others.
Semantic-UI react pagination component
Semantic UI React is the official React integration for Semantic UI. The library has the following great features:
- jQuery Free;
- Declarative API;
- Augmentation;
- Shorthand Props;
- Sub Components;
- Auto Controlled State.
The pagination component has a good simple design and integrates to the existing app very smoothly. It also has several options on how to developer pagination:
- A pagination component can be disabled;
- Pagination can be a controlled component;
- Pagination has configurable options;
- Pagination is a wrapper for the Menu component, you can use * Menu props with Pagination;
- Pagination has support for a shorthand API for its items.
Rsuite Js react pagination component
React Suite is a library of React components, designed for the middle platform and back-end products. Committed to creating intimate interactive designs while providing developers with a friendly development experience. The library is pretty popular and has almost 6k stars on Github.
As for the pagination component it is very simple but yet good for use in the basic react applications with the following options:
- You can change the size of the pagination component;
- You can disable it;
- You can also use some of the advanced features like adding boundary links, showing last and first pages, and adding arrows;
- There are also dozens of props available.
React table pagination component
React Table is one of the most popular table libraries in React. It has almost 15,000 stars on GitHub. The react-table library is very lightweight and offers all the basic features necessary for any simple table. Now, after version 7 was released, it also supports Hooks.
The pagination components in this library are a part of the options available when you are developing a react table. Thus, you can use this react pagination component only with react table library.
Conclusion
In this tutorial, you have made a react pagination component using a ready-made library. You also learned how to make a request to the server and set up a basic full-stack react application.
We have also attached the source code of our application so that you can use it in your further development.
Additionally you can check how we developed react pagination components in our ready-made React Templates.
About Flatlogic
At Flatlogic, we help businesses to speed up web development with our beautifully designed web & mobile application templates built with React, Vue, Angular, React Native, and Bootstrap. During the last several years we have successfully delivered more than 100 custom dashboards and data management solutions to various clients starting from innovative startups to established and respected enterprises.
You might also like these articles:
Javascript Tabs: Save Space! Examples Of Tabbed Widgets
React Table Guide And Best React Table Examples
12 JavaScript Image Manipulation Libraries For Your Next Web App
Top comments (0)