In this article, we learn how to use AgGrid in React App.
First, open our React project and install AgGrid dependency.
npm install ag-grid-community npm install ag-grid-react
Then import CSS from ag-grid-community.
import 'ag-grid-community/dist/styles/ag-grid.css'; import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
For column data, we need headerName and field. the field name is matched with the row data property.
const columnDefs = [ { headerName: 'Car Name', field: 'Car' }, { headerName: 'Model Name', field: 'Model' }, { headerName: 'Price', field: 'Price' } ]
Row data have the column filed name data.
const rowData = [ { Car: "Audi", Model: "R8", Price: '2.30 Cr' }, { Car: "BMW", Model: "VBX6", Price: '1.04 Cr' }, { Car: "Marcedes", Model: "Mercedes-AMG A 35", Price: '3.08 Cr' } ]
Here row data property match with the column data field name and set data in the table.
Now import AgGridReact in ag-grid-react and give them row data and column data.
<AgGridReact rowData={rowData} columnDefs={columnDefs} />
So, my App.js look like this,
import React from 'react'; import { AgGridReact } from 'ag-grid-react'; import 'ag-grid-community/dist/styles/ag-grid.css'; import 'ag-grid-community/dist/styles/ag-theme-alpine.css'; const App = () => { const rowData = [ { Car: "Audi", Model: "R8", Price: '2.30 Cr' }, { Car: "BMW", Model: "VBX6", Price: '1.04 Cr' }, { Car: "Marcedes", Model: "Mercedes-AMG A 35", Price: '3.08 Cr' } ] const columnDefs = [ { headerName: 'Car Name', field: 'Car' }, { headerName: 'Model Name', field: 'Model' }, { headerName: 'Price', field: 'Price' } ] return ( <div className="ag-theme-alpine" style={{ height: 200, width: 600 }}> <AgGridReact rowData={rowData} columnDefs={columnDefs} /> </div> ) } export default App
Output:-