article

Tuesday, September 28, 2021

ReactJS How to load data API in AG Grid React with loading content and Pagination

ReactJS How to load data API in AG Grid React with loading content and Pagination

In this tutorial we will create a load data API in AG Grid React with loading content and Pagination

AG Grid is a fully-featured and highly customizable JavaScript data grid. It delivers outstanding performance, has no 3rd party dependencies and integrates smoothly with React as React Component.

C:\reactdev\myreactdev>npm install --save ag-grid-community

https://www.npmjs.com/package/ag-grid-community

C:\reactdev\myreactdev>npm i --save ag-grid-community ag-grid-react react-dom-factories

https://www.npmjs.com/package/ag-grid-react

https://reqres.in/
Test your front-end against a real API

https://reqres.in/api/users
src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/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

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

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

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

  return (
    <div className="App">
      <h2>ReactJS How to load data API in AG Grid React with loading content and Pagination </h2>
      <div className="ag-theme-alpine ag-style">
        <AgGridReact
          pagination={true}
          rowModelType={'infinite'}
          paginationPageSize={perPage}
          cacheBlockSize={perPage}
          onGridReady={onGridReady}
          rowHeight={60}
          defaultColDef={{ flex: 1 }}
          overlayLoadingTemplate={
            '<span className="ag-overlay-loading-center">Please wait while your rows are loading...</span>'
          }
          overlayNoRowsTemplate={
            '<span className="ag-overlay-loading-center">No data found to display.</span>'
          }
        >
          <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" />
        </AgGridReact>
      </div>
    </div>
  );
}

export default App;
src/App.css
//src/App.css
.App {
  padding: 50px;
}
.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;
}

Related Post