Clue Mediator

Load data from the API in React AG Grid

📅May 20, 2021

Today we’ll show you how to load data from the API in React AG Grid.

In the previous article, we have implemented the React AG Grid with the static data. Checkout several examples on the DataTable.

You may also like the following articles on ReactJS.

Demo Application

Output - AG Grid in React - Clue Mediator

Output - AG Grid in React - Clue Mediator

Steps to load data from the API in React AG Grid

  1. Implement AG Grid in React
  2. Call API to load the data in Grid
  3. Output

1. Implement AG Grid in React

Let’s create a react application using the `create-react-app` and implement AG Grid in React. Check the following article for more information.

How to implement AG Grid in React

2. Call an API to load the data in Grid

Use the useEffect and useState to call an API and store data in the state variable using React Hooks.

const [rowData, setRowData] = useState([]);

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

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

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">
  }

  return (
    <div class="App">
      <h2>Implement AG Grid in React - <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} 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">
        </aggridcolumn></aggridcolumn></aggridcolumn></aggridcolumn></aggridreact>
      </div>
    </div>
  );
}

export default App;

3. Output

Now, run the react application and check the output in the browser.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project