React : Implementing Server-Side Pagination in React and .NET Core C#

Server-side pagination is essential for managing large datasets efficiently in web applications. In this blog post, we'll explore how to implement server-side pagination using React for the frontend and .NET Core for the backend. By fetching data from the server in chunks, we can improve performance and user experience while handling large datasets.
Step 1: Set Up the .NET Core Web API:
Begin by creating a .NET Core Web API project to serve as the backend for our pagination example. Define endpoints to retrieve paginated data from the server.
Create a .NET Core Web API Project:
dotnet new webapi -n PaginationAPI
cd PaginationAPI
Define a Model:
Create a simple model class to represent the data entity.
// DataModel.cs
public class DataModel
{
public int Id { get; set; }
public string Name { get; set; }
// Add more properties as needed
}
an example of setting up a mock repository in a .NET Core Web API project using Entity Framework Core to connect to a SQL database.
Install Entity Framework Core:
Ensure you have Entity Framework Core installed in your project. You can install it via NuGet Package Manager or .NET CLI.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Set Up DbContext: Create a DbContext class to represent the database context and define a DbSet for your model.
// DataContext.cs
using Microsoft.EntityFrameworkCore;
public class DataContext : DbContext
{
public DbSet<DataModel> Data { get; set; }
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure entity mappings, relationships, etc.
}
}
Configure Connection String: Update your appsettings.json file to include the connection string for your SQL Server database.
// appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=YourDatabaseName;User=YourUsername;Password=YourPassword;"
}
}
Register DbContext in Dependency Injection Container: Configure your DbContext in the ConfigureServices method of the Startup class.
// Startup.cs
using Microsoft.EntityFrameworkCore;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IDataRepository, DataRepository>();
services.AddControllers();
}
Create Repository Interface: Define an interface for your repository.
// IDataRepository.cs
using System.Collections.Generic;
public interface IDataRepository
{
IEnumerable<DataModel> GetData();
// Add more methods as needed
}
Implement Repository Class: Create a repository class that implements the interface and interacts with the DbContext.
// DataRepository.cs
using System.Collections.Generic;
using System.Linq;
public class DataRepository : IDataRepository
{
private readonly DataContext _context;
public DataRepository(DataContext context)
{
_context = context;
}
public IEnumerable<DataModel> GetData()
{
return _context.Data.ToList();
}
// Implement additional repository methods as needed
}
With these steps, you have set up a mock repository in your .NET Core Web API project using Entity Framework Core to connect to a SQL database. You can now use this repository to interact with your database and perform CRUD operations on your data entities.
Step 2: Implement Server-Side Pagination in .NET Core: Create a controller to handle requests for paginated data.
// DataController.cs
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
[ApiController]
public class DataController : ControllerBase
{
private readonly MockRepository _repository;
public DataController(MockRepository repository)
{
_repository = repository;
}
[HttpGet]
public IActionResult GetPaginatedData(int page = 1, int pageSize = 10)
{
var data = _repository.GetData();
var paginatedData = data.Skip((page - 1) * pageSize).Take(pageSize);
return Ok(paginatedData);
}
}
Step 3: Set Up React Application: Generate a new React application using Create React App or any other preferred method. This will serve as the frontend for our pagination example.
npx create-react-app pagination-app
cd pagination-app
Step 4: Implement Pagination Component in React: Create a pagination component in React to allow users to navigate through pages and fetch paginated data from the server.
// PaginationComponent.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const PaginationComponent = () => {
const [data, setData] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
useEffect(() => {
fetchData();
}, [currentPage]);
const fetchData = async () => {
try {
const response = await axios.get(`/api/data?page=${currentPage}`);
setData(response.data);
// Calculate total pages based on response
setTotalPages(10); // Example: Assuming 10 total pages
} catch (error) {
console.error('Error fetching data:', error);
}
};
const goToPage = (page) => {
setCurrentPage(page);
};
return (
<div>
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
<div>
{Array.from({ length: totalPages }).map((_, index) => (
<button key={index + 1} onClick={() => goToPage(index + 1)}>{index + 1}</button>
))}
</div>
</div>
);
};
export default PaginationComponent;
Step 5: Incorporate Pagination Component into App Component: Integrate the pagination component into your main App component to display paginated data in your React application.
// App.js
import React from 'react';
import PaginationComponent from './PaginationComponent';
const App = () => {
return (
<div>
<h1>Pagination Example</h1>
<PaginationComponent />
</div>
);
};
export default App;
Conclusion: By following the steps outlined in this blog post, you can implement server-side pagination in your React and .NET Core web application. Server-side pagination helps optimize performance and manage large datasets efficiently, providing a seamless user experience. With React handling the frontend and .NET Core powering the backend, you can create robust and scalable web applications capable of handling significant amounts of data.