article

Monday, November 29, 2021

ReactJS AG Grid fetch json

ReactJS AG Grid fetch json

In this tutorial we will create a sample to load static data in a grid.

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

Module not found: Can't resolve 'ag-grid-react' in 'C:\reactdev\myreactdev\src'
C:\reactdev\myreactdev>npm i --save ag-grid-community ag-grid-react react-dom-factories

https://www.npmjs.com/package/ag-grid-react
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 { 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 [rowData, setRowData] = useState([]);

  useEffect(() => {
    fetch('https://reqres.in/api/users?per_page=12')
      .then(res => res.json())
      .then(result => setRowData(result.data));
  }, []);

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

  return (
    <div className="App">
      <h2>ReactJS AG Grid fetch json</h2>
      <div className="ag-theme-alpine ag-style">
        <AgGridReact
          defaultColDef={{ flex: 1 }}
          rowHeight={60}
          rowData={rowData} >
          <AgGridColumn field="first_name" headerName="First Name" sortable={true} filter={true} cellClass="vertical-middle" />
          <AgGridColumn field="last_name" headerName="Last Name" sortable={true} filter={true} cellClass="vertical-middle" />
          <AgGridColumn field="email" headerName="Email" sortable={true} filter={true} cellClass="vertical-middle" />
          <AgGridColumn field="avatar" headerName="Avatar" sortable={true} filter={true} cellRendererFramework={avatarFormatter} cellClass="vertical-middle" />
        </AgGridReact>
      </div>
    </div>
  );
}

export default App;
src/App.css
//src/App.css
.ag-style {
  height: 500px;
  width: 100%;
}

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

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

Related Post