Initializing AG Grid in a React Component
Showcase how to set up AG Grid within a React functional component, including defining column definitions and row data.
import React, { useState, useEffect, useMemo } from 'react';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
Imports necessary React hooks, the AgGridReact component, and AG Grid styles.
const MyAgGridComponent = () => {
const [rowData, setRowData] = useState([]);
useEffect(() => {
fetch('https://www.ag-grid.com/example-assets/row-data.json')
.then(result => result.json())
.then(rowData => setRowData(rowData));
}, []);
Defines the component and uses useState to manage row data. useEffect is used to fetch row data from a URL and update the state.
const columnDefs = useMemo(() => [
{ field: 'make', sortable: true, filter: true },
{ field: 'model', sortable: true, filter: true },
{ field: 'price', filter: 'agNumberColumnFilter' }
], []);
Uses useMemo to memorize the column definitions, improving performance by avoiding unnecessary recalculations on re-renders.
return (
<div className="ag-theme-alpine" style={{ height: '500px', width: '600px' }}>
<AgGridReact
rowData={rowData}
columnDefs={columnDefs}
animateRows={true}
rowSelection="multiple"
></AgGridReact>
</div>
);
};
Renders an AG Grid table with the defined row data and column definitions, enabling animations and multiple row selection.
export default MyAgGridComponent;
Exports the component for use in other parts of the application.