Clue Mediator

Implement server side pagination in React AG Grid

📅June 5, 2021

Today we’ll show you how to implement server side pagination in React AG Grid.

In the previous article, we have implemented client side pagination using React AG Grid but now we will add server side pagination.

Checkout more articles on ReactJS

Demo Application

Output - Implement server side pagination in React AG Grid - Clue Mediator

Output - Implement server side pagination in React AG Grid - Clue Mediator

Steps to implement server side pagination using React AG Grid

  1. Add AG Grid and define columns
  2. Configure the pagination option
  3. Place an API with server side pagination
  4. Output

1. Add AG Grid and define columns

First of all, we will simply add the AG Grid by installing the `ag-grid-community` and `ag-grid-react` packages.

Check the following article to implement AG Grid with static data.
How to implement AG Grid in React

Use the following CSS file and React component without data binding for startup.

App.css

.ag-style {
  height: 280px;
  width: 100%;
}

.vertical-middle {
  display: flex;
  align-items: center;
}

.vertical-middle img {
  display: block;
  border: 1px solid #ddd;
  border-radius: 3px;
}

App.js

import React from 'react';
import { AgGridColumn, AgGridReact } from 'ag-grid-react';

import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

import './App.css';

function App() {

  const avatarFormatter = ({ value }) => {
    return <img src={value} width="50px" height="50px">
  }

  return (
    <div class="App">
      <h2>Server side pagination in the React AG Grid - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h2>
      <div class="ag-theme-alpine ag-style">
        <aggridreact 1="" defaultcoldef={{ flex: }} rowheight={60}>
          <aggridcolumn field="first_name" headername="First Name" cellclass="vertical-middle">
          <aggridcolumn field="last_name" headername="Last Name" cellclass="vertical-middle">
          <aggridcolumn field="email" headername="Email" cellclass="vertical-middle">
          <aggridcolumn field="avatar" headername="Avatar" cellrendererframework={avatarFormatter} cellclass="vertical-middle">
        </aggridcolumn></aggridcolumn></aggridcolumn></aggridcolumn></aggridreact>
      </div>
    </div>
  );
}

export default App;

2. Configure the pagination option

Let’s configure the pagination option by adding the following properties in the grid. Here, we have set `perPage = 3` to capture the 3 records per page.

function App() {
  const perPage = 3;

  ...
  ...

  return (
    ...
    ...
      <aggridreact ...="" pagination={true} rowmodeltype={'infinite'} paginationpagesize={perPage} cacheblocksize={perPage}>
        ...
        ...
      </aggridreact>
    ...
    ...
  );
}

export default App;

3. Place an API with server side pagination

Now, we will use the `onGridReady` event callback to get the grid API and column API. Set the Datasource after the grid is initialised.

Here, we will use the `getRows` function to call an API with pagination parameters such as `startRow`, `endRow`, etc.

Look at the following code, where we have used the reqres.in fake API for pagination.

function App() {
  const [gridApi, setGridApi] = useState(null);
  const perPage = 3;

  const onGridReady = (params) => {
    setGridApi(params.api);
  };

  useEffect(() => {
    if (gridApi) {
      const dataSource = {
        getRows: (params) => {
          // Use startRow and endRow for sending pagination to Backend
          // params.startRow : Start Page
          // params.endRow : End Page

          const page = params.endRow / perPage;
          fetch(`https://reqres.in/api/users?per_page=${perPage}&page=${page}`)
            .then(resp => resp.json())
            .then(res => {
              params.successCallback(res.data, res.total);
            }).catch(err => {
              params.successCallback([], 0);
            });
        }
      }

      gridApi.setDatasource(dataSource);
    }
  }, [gridApi]);

  ...
  ...

  return (
    <aggridreact ...="" ongridready={onGridReady}>
      ...
      ...
    </aggridreact>
  );
}

export default App;

4. Output

Let’s pull all the code together and see how it looks.

App.js

import React, { useEffect, useState } from 'react';
import { AgGridColumn, AgGridReact } from 'ag-grid-react';

import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

import './App.css';

function App() {
  const [gridApi, setGridApi] = useState(null);
  const perPage = 3;

  const onGridReady = (params) => {
    setGridApi(params.api);
  };

  useEffect(() => {
    if (gridApi) {
      const dataSource = {
        getRows: (params) => {
          // Use startRow and endRow for sending pagination to Backend
          // params.startRow : Start Page
          // params.endRow : End Page

          const page = params.endRow / perPage;
          fetch(`https://reqres.in/api/users?per_page=${perPage}&page=${page}`)
            .then(resp => resp.json())
            .then(res => {
              params.successCallback(res.data, res.total);
            }).catch(err => {
              params.successCallback([], 0);
            });
        }
      }

      gridApi.setDatasource(dataSource);
    }
  }, [gridApi]);

  const avatarFormatter = ({ value }) => {
    return <img src={value} width="50px" height="50px">
  }

  return (
    <div class="App">
      <h2>Server side pagination in the React AG Grid - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h2>
      <div class="ag-theme-alpine ag-style">
        <aggridreact 1="" pagination={true} rowmodeltype={'infinite'} paginationpagesize={perPage} cacheblocksize={perPage} ongridready={onGridReady} rowheight={60} defaultcoldef={{ flex: }}>
          <aggridcolumn field="first_name" headername="First Name" cellclass="vertical-middle">
          <aggridcolumn field="last_name" headername="Last Name" cellclass="vertical-middle">
          <aggridcolumn field="email" headername="Email" cellclass="vertical-middle">
          <aggridcolumn field="avatar" headername="Avatar" cellrendererframework={avatarFormatter} cellclass="vertical-middle">
        </aggridcolumn></aggridcolumn></aggridcolumn></aggridcolumn></aggridreact>
      </div>
    </div>
  );
}

export default App;

Run the react app and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project