Pagination In ReactJS Using Web API And SQL

Introduction 

 
In this article, I'm going to create an application to perform pagination in React Js with Axios using Web API with the help of an example. The backend is a SQL Server database. Pagination is navigation which lets you split a huge amount of content within a set of tables into smaller parts. A Web API is used to provide data connectivity between the database and the front end application and building Restful services. On the UI side, I will use react-bootstrap to create a rich, interactive, device-independent user experience and For building a beautiful UI. In this example, I will bind employee details and we will perform pagination. Let us see step by step.
 
First, take a look at our output:
 
Pagination In ReactJS Using Web API And SQL
 
I'm using Visual Studio Code as a tool to build my application. If you don't have Visual studio code in your system then first you have to download and install. Here is the Visual Studio Code download link: Download Visual Studio Code Editor.
 
Prerequisites
  1. Visual studio
  2. SQL Server
  3. Node.js version > 10
  4. React
  5. React Axios
  6. Visual studio code
  7. Bootstrap
  8. React-bootstrap
Step1 - Create a database and table
 
Create a database. Open SQL Server and create a new database and table. As you can see from the following query, I have created a database table called Employees
 
Employees
  1. CREATE TABLE [dbo].[Employees](  
  2.    [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.    [Name] [nvarchar](50) NULL,  
  4.    [Gender] [nvarchar](10) NULL,  
  5.    [Salary] [intNULL  
  6. )  
  7. INSERT Employees VALUES('Ron','Male',7871)  
  8. INSERT Employees VALUES('Pete','Male',7871)  
  9. INSERT Employees VALUES('Steve','Male',7871)  
  10. INSERT Employees VALUES('Steve','Male',7871)  
  11. INSERT Employees VALUES('Ravi','Male',7871)  
  12. INSERT Employees VALUES('Raj','Male',7871)  
  13. INSERT Employees VALUES('Kiran','Male',7871)  
  14. INSERT Employees VALUES('Ron','Male',7871)  
  15. INSERT Employees VALUES('Pete','Male',7871)  
  16. INSERT Employees VALUES('Steve','Male',7871)  
  17. INSERT Employees VALUES('Steve','Male',7871)  
  18. INSERT Employees VALUES('Ravi','Male',7871)  
  19. INSERT Employees VALUES('Raj','Male',7871)  
  20. INSERT Employees VALUES('Kiran','Male',7871)  
  21. INSERT Employees VALUES('Ron','Male',7871)  
  22. INSERT Employees VALUES('Pete','Male',7871)  
  23. INSERT Employees VALUES('Steve','Male',7871)  
  24. INSERT Employees VALUES('Steve','Male',7871)  
  25. INSERT Employees VALUES('Ravi','Male',7871)  
  26. INSERT Employees VALUES('Raj','Male',7871)  
  27. INSERT Employees VALUES('Kiran','Male',7871)  
Note

You can choose the size of the column according to your requirements.
 
Step 2. Create a Web API Project

Now, we will create a Web API with the functionality of binding records from a database. Go to Visual Studio >> File >> New >> Project, and select Web Application. After that, click OK and you will see the templates. Select the Web API template.
 
Pagination In ReactJS Using Web API And SQL
 
Click Web API
 
Pagination In ReactJS Using Web API And SQL
 
Click OK.
 
Step 3. Add ADO.NET Entity Data Model
 
Now, Select Models folder >> Right-click >> Add >> New Item >> select Data in left panel >> ADO.NET Entity Data Model,
 
Pagination In ReactJS Using Web API And SQL
 
Click Add button
 
Pagination In ReactJS Using Web API And SQL
 
Click Next button
 
Pagination In ReactJS Using Web API And SQL
 
Give the server name of the SQL server and its credentials, then select database and test connection. Then, click the OK button.
 
Pagination In ReactJS Using Web API And SQL
 
Click the Next button
 
Pagination In ReactJS Using Web API And SQL
 
Select tables and click Finish button
 
See our table entity:
 
 
Pagination In ReactJS Using Web API And SQL
 
Step 4. Add API controller logic
 
Befor the write of the controller logice neee to add a view model class for return employee list with count. So now right click on model folder and add a class as below mentioned.
  1. public class EmployeeViewModel {  
  2.     public int TotalCount {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public IEnumerable < Employee > employees {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
Now, Go to the Controller folder in our API Application and Right-click >> Add >> Controller >> Select Web API 2 Controller-Empty
 
Pagination In ReactJS Using Web API And SQL
 
Click the Add button. Now we will write the logic to bind the data and perform pagination. We will go to the controller class and set the routing to make it more user-friendly by writing the below code.
  1. using System;  
  2. using System.Linq;  
  3. using System.Web.Http;  
  4. using PaginationApi.Models;  
  5. namespace PaginationApi.Controllers {  
  6.     [RoutePrefix("Api/Employee")]  
  7.     public class EmployeeAPIController: ApiController {  
  8.         [HttpGet]  
  9.         [Route("GetEmpDetails")]  
  10.         public EmployeeViewModel GetEmaployee(int pageNo) {  
  11.             int skipPage = (pageNo - 1) * 5;  
  12.             EmployeeViewModel objEmp = new EmployeeViewModel();  
  13.             try {  
  14.                 TestDBEntities objEntity = new TestDBEntities();  
  15.                 int totalCount = objEntity.Employees.Count();  
  16.                 var result = objEntity.Employees.OrderBy(a => a.Id).Skip(skipPage).Take(5).ToList();  
  17.                 objEmp.TotalCount = totalCount;  
  18.                 objEmp.employees = result;  
  19.                 return objEmp;  
  20.             } catch (Exception) {  
  21.                 throw;  
  22.             }  
  23.         }  
  24.     }  
  25. }  
Now, our API has been completed. As you may see from the above code, it has the functionality to bind and pagination of the records.
 
Step 5.Create and Install React js
 
Now we will create a react project thought below command. But before that just check Node and NPM installed or not. And also We are using Visual Studio code as writing angular code for UI application so first, make sure it installed or not. If you have not installed then go to this link for download.
 
Let's create a react project to open a new terminal and run the following command to install and create a react project.
 
npx create-react-app pagination-app
 
Pagination In ReactJS Using Web API And SQL
 
The React project has been created.
 
Step 6. Set Visual studio code for react code
 
Open Visual Studio Code and go inside the folder. Open the project inside the visual studio code.
 
Pagination In ReactJS Using Web API And SQL
Select folder
 
Pagination In ReactJS Using Web API And SQL
 
Look our folder structure
 
Pagination In ReactJS Using Web API And SQL
 
Step 7. Install bootstrap
 
Now, we will install bootstrap to building a beautiful UI of our react application.
 
npm install bootstrap --save 
 
Next, we  will install react-bootstrap bootstrap for design table, button, etc
 
npm install react-bootstrap bootstrap
 
Pagination In ReactJS Using Web API And SQL
 
Step 8. Install Axios library
 
Axios is a modern and promise based java scrip HTTP client library which is works asynchronously and allows us to make HTTP calls and consume to REST API.
 
Let's install Axios in our React project using the following command:
 
npm install --save axios
 
Pagination In ReactJS Using Web API And SQL
 
Step 9. React-bootstrap-table2
 
install React-bootstrap-table2 in our React project using the following command.
 
npm i react-bootstrap-table-2 or npm i react-bootstrap-table2-paginaton
Pagination In ReactJS Using Web API And SQL
Step 10. Check to react dependency
 
Go to the in package.json file and check to react dependency.
 
Pagination In ReactJS Using Web API And SQL
 
Step 11. Add React Component
 
Go to the inside of the src folder and create a new folder. Here, I created a Demo folder and 2 files.
  • EmployeeList.js
  • EmployeePagination.js
Pagination In ReactJS Using Web API And SQL
Step 12. Write code in js file to perform our operation
 
Now we will write our logic for performing pagination operation.
 
Open EmployeePagination.js and write code for pagination. First import dependency libraries
  1. import React from 'react'  
  2. import BootstrapTable from 'react-bootstrap-table-next';  
  3. import paginationFactory, { PaginationProvider, PaginationListStandalone } from 'react-bootstrap-table2-paginator';  
  4. export default function EmployeePagination({ data, page, sizePerPage, onTableChange, totalSize, columns }) {  
  5.    return (  
  6.       <div>  
  7.          <PaginationProvider  
  8.          pagination={  
  9.             paginationFactory({  
  10.             custom: true,  
  11.             page,  
  12.             sizePerPage,  
  13.             totalSize  
  14.             })  
  15.          }  
  16.         >  
  17.       {  
  18.          ({  
  19.             paginationProps,  
  20.             paginationTableProps  
  21.           }) => (  
  22.       <div>  
  23.          <BootstrapTable  
  24.             remote  
  25.             keyField="Id"  
  26.             data={data}  
  27.             columns={columns}  
  28.             onTableChange={onTableChange}  
  29.             {...paginationTableProps}  
  30.           />  
  31.       <div>  
  32.    <PaginationListStandalone  
  33.          {...paginationProps}  
  34.          />  
  35.      </div>  
  36.    </div>  
  37.    )  
  38.    }  
  39.   </PaginationProvider>  
  40.   </div>  
  41.  )  
  42. }  
Now again, go inside the Demo folder and open EmployeeList.js file. First import necessary library, then write below code. In the file:
  • Declare the properties in the state
  • Create Columns and set the style of the column inside render method
  • Create a method for bind the records and call inside component did mount
  • Design and call the employee pagination inside the return
  • Create a page handler method for pagination
  1. import React from 'react';  
  2. import {  
  3.     Row,  
  4.     Col,  
  5.     Container  
  6. } from 'react-bootstrap';  
  7. import Axios from 'axios';  
  8. import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';  
  9. import EmployeePagination from './EmployeePagination';  
  10. import 'bootstrap/dist/css/bootstrap.css';  
  11. const apiUrl = "http://localhost:51393/Api/Employee";  
  12. class EmployeeList extends React.Component {  
  13.     constructor(props) {  
  14.         super(props);  
  15.         this.state = {  
  16.             error: null,  
  17.             response: {},  
  18.             CurrentPage: 1,  
  19.             data: [],  
  20.             filter: {  
  21.                 pageNo: 1,  
  22.                 sizePerPage: 5,  
  23.             },  
  24.             totalCount: 0,  
  25.         }  
  26.     }  
  27.     componentDidMount() {  
  28.         this.bindData();  
  29.     }  
  30.     bindData() {  
  31.         let {  
  32.             pageNo  
  33.         } = this.state.filter;  
  34.         Axios.get(apiUrl + `/GetEmpDetails?pageNo=${pageNo}`).then(response => response.data).then(  
  35.             (result) => {  
  36.                 this.setState({  
  37.                     data: result.employees,  
  38.                     totalCount: result.TotalCount  
  39.                 });  
  40.             },  
  41.             (error) => {  
  42.                 this.setState({  
  43.                     error  
  44.                 });  
  45.             })  
  46.     }  
  47.     onPageHandler = async (type, {  
  48.         page  
  49.     }) => {  
  50.         let data = page  
  51.         let {  
  52.             filter  
  53.         } = this.state;  
  54.         let tempFilter = {  
  55.             ...filter  
  56.         };  
  57.         tempFilter["pageNo"] = data;  
  58.         await this.setState({  
  59.             filter: tempFilter  
  60.         })  
  61.         this.bindData()  
  62.     }  
  63.     render() {  
  64.         //Column Style  
  65.         const colStyle = {  
  66.             backgroundColor: '#002b48',  
  67.             color: "#ffffff",  
  68.             width: '60px'  
  69.         }  
  70.         //Generate column  
  71.         const columns = [{  
  72.             dataField: 'Id',  
  73.             text: 'Id',  
  74.             headerStyle: colStyle  
  75.         }, {  
  76.             dataField: 'Name',  
  77.             text: 'Name',  
  78.             headerStyle: colStyle  
  79.         }, {  
  80.             dataField: 'Gender',  
  81.             text: 'Gender',  
  82.             headerStyle: colStyle  
  83.         }, {  
  84.             dataField: 'Salary',  
  85.             text: 'Salary',  
  86.             headerStyle: colStyle  
  87.         }];  
  88.         const {  
  89.             filter,  
  90.             data  
  91.         } = this.state;  
  92.         return ( < React.Fragment > < Container > < Row > < Col > < h2 > Pagination Demo in React < /h2></Col > < /Row> < hr > < /hr> < Row > < Col xs = {  
  93.                 3  
  94.             } > < /Col> < Col xs = {  
  95.                 6  
  96.             } > < EmployeePagination data = {  
  97.                 data  
  98.             }  
  99.             page = {  
  100.                 filter.pageNo  
  101.             }  
  102.             sizePerPage = {  
  103.                 filter.sizePerPage || 5  
  104.             }  
  105.             totalSize = {  
  106.                 this.state.totalCount  
  107.             }  
  108.             onTableChange = {  
  109.                 this.onPageHandler  
  110.             }  
  111.             columns = {  
  112.                 columns  
  113.             }  
  114.             /> < /Col> < Col xs = {  
  115.                 3  
  116.             } > < /Col> < /Row> < /Container> < /React.Fragment>)  
  117.     }  
  118. }  
  119. export default EmployeeList;  
Finally, open index.js file and import the necessary library, then write the below code.
  1. import React from 'react';  
  2. import './App.css';  
  3. import EmployeeList from './Demo/EmployeeList';  
  4. function App() {  
  5.    return (  
  6.       <div className="App">  
  7.          <EmployeeList/>  
  8.       </div>  
  9.       );  
  10.    }  
  11. export default App;  
Finally, our coding part also has been completed.
 
Step 13. Set CORS (Cross-Origin Resource Sharing)
 
Go to the Web API project.
 
Download a NuGet package for CORS. Go to NuGet Package Manager and download the following file.
 
After that, go to the App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
 
Pagination In ReactJS Using Web API And SQL
 
Add namespace
 
Using System.Web.Http.Cors;
 
After that, add the below code inside Register method.
 
var cors = newEnableCorsAttribute("*", "*", "*"); 
config.EnableCors(cors);
 
Step 14. Run
 
We have completed all the needed code functionality for our functionality. Before running the application, first, make sure to save your work.
 
Now, let's run the app and see how it works.
 
Open TERMINAL and write the following command to run the program.
 
npm start
 
The output looks like the following image. It's a stunning UI that's been created.
 
Pagination In ReactJS Using Web API And SQL
 
Click on next button
 

Conclusion

 
We have completed an operation to get pagination in our table records in React and Axios using Web API and SQL server and we have started by installing and creating the create-react-app, then used it to create our React project. Next, we installed bootstrap and react-bootstrap and react-bootstrap-table-next in react application. After that, we installed the Axios client library
 
I hope this article will help you with your pagination functionality. Please post your feedback, questions, or comments about this article.