Creating Your First AG-Grid Table in React
Welcome back to our AG-Grid React series! In this installment, we're diving into the exciting world of AG-Grid by creating our very first interactive data table. AG-Grid is a powerful, enterprise-grade data grid that brings advanced functionalities like sorting, filtering, pagination, and more to your React applications with remarkable ease.
If you're looking to display tabular data efficiently and beautifully, AG-Grid is an excellent choice. This post will guide you step-by-step through setting up a basic grid, defining your data, and configuring your columns.
Prerequisites: Getting Started
Before we jump into the code, ensure you have a React project set up. If you don't, you can quickly create one using Create React App or Vite:
npx create-react-app my-aggrid-app
cd my-aggrid-app
# or
npm create vite@latest my-aggrid-app -- --template react
cd my-aggrid-app
npm install
Next, we need to install the necessary AG-Grid packages: ag-grid-community (the core grid library) and ag-grid-react (the React component wrapper).
npm install ag-grid-community ag-grid-react
# or
yarn add ag-grid-community ag-grid-react
The Core: AgGridReact Component
The heart of using AG-Grid in React is the <AgGridReact /> component. This component takes several props, but for our first table, two are absolutely essential:
-
rowData: An array of JavaScript objects, where each object represents a row in your grid. -
columnDefs: An array of JavaScript objects, where each object defines a column in your grid.
Defining Your Data (rowData)
The rowData prop expects an array of objects. Each object in this array corresponds to a single row in your table. The keys of these objects are crucial, as they will be used to map data to specific columns.
Let's imagine we want to display a list of cars:
const rowData = [
{ make: "Toyota", model: "Celica", price: 35000 },
{ make: "Ford", model: "Mondeo", price: 32000 },
{ make: "Porsche", model: "Boxster", price: 72000 }
];
Defining Your Columns (columnDefs)
The columnDefs prop is an array of objects, where each object configures a column. At a minimum, each column definition object needs a field property. This field must match a key in your rowData objects.
You can also provide a headerName for a more user-friendly column title, and enable basic features like sortable and filter directly in the column definition.
const columnDefs = [
{ field: "make", headerName: "Car Make", sortable: true, filter: true },
{ field: "model", headerName: "Car Model", sortable: true, filter: true },
{ field: "price", headerName: "Price (USD)", sortable: true, filter: true }
];
Assembling Your First Grid
Now that we have our data and column definitions, let's put them together in a React component. We'll use React's useState hook to manage our rowData and columnDefs.
It's also essential to import AG-Grid's CSS themes and provide a container div for the grid with defined dimensions (height and width) for it to render correctly.
import React, { useState, useMemo } from 'react';
import { AgGridReact } from 'ag-grid-react'; // the AG-Grid React Component
// Import AG-Grid themes
import 'ag-grid-community/styles/ag-grid.css'; // Core grid CSS
import 'ag-grid-community/styles/ag-theme-alpine.css'; // A theme for the grid
function MyFirstGrid() {
// Row Data: The data to be displayed.
const [rowData, setRowData] = useState([
{ make: "Toyota", model: "Celica", price: 35000 },
{ make: "Ford", model: "Mondeo", price: 32000 },
{ make: "Porsche", model: "Boxster", price: 72000 },
{ make: "BMW", model: "M3", price: 60000 },
{ make: "Mercedes", model: "C-Class", price: 45000 },
]);
// Column Definitions: Defines the columns to be displayed.
const [columnDefs, setColumnDefs] = useState([
{ field: "make", headerName: "Car Make", sortable: true, filter: true, flex: 1 },
{ field: "model", headerName: "Car Model", sortable: true, filter: true, flex: 1 },
{ field: "price", headerName: "Price (USD)", sortable: true, filter: true, flex: 1 },
]);
// Default Column Definition: Applied to all columns unless overridden.
const defaultColDef = useMemo(() => ({
resizable: true, // Enable column resizing by default
minWidth: 100, // Minimum width for columns
}), []);
return (
<div style={{ height: 400, width: '100%' }} className="ag-theme-alpine">
<AgGridReact
rowData={rowData}
columnDefs={columnDefs}
defaultColDef={defaultColDef}
></AgGridReact>
</div>
);
}
export default MyFirstGrid;
In the example above, we've done the following:
- Imported
AgGridReactand the necessary CSS styles. - Used
useStateto manage ourrowDataandcolumnDefs. - Wrapped the
<AgGridReact />component in a<div>that has a definedheightandwidth. This is crucial for AG-Grid to render properly. - Applied the
ag-theme-alpineclass to the containerdivto give our grid a clean, modern look. - Introduced
defaultColDefwithuseMemo, which allows you to set default properties (likeresizable) for all columns without specifying them repeatedly. - Added
flex: 1to each column definition, which makes the columns expand to fill the available width of the grid evenly.
Exploring Basic Grid Features
Notice how we added sortable: true and filter: true to each column definition. This immediately enables powerful features:
- Sorting: Click on a column header (e.g., "Car Make") to sort the data ascending or descending.
- Filtering: Hover over a column header and click the menu icon (three horizontal lines) to reveal a filter input. You can type to filter the rows based on that column's content.
These are just two examples of the many features AG-Grid offers right out of the box with minimal configuration.
Next Steps
Congratulations! You've successfully created your first AG-Grid table in React. This foundational setup opens the door to a world of possibilities. From here, you can start exploring more advanced topics such as:
- Customizing cell renderers and editors.
- Implementing pagination and infinite scrolling.
- Working with selection models (row and cell selection).
- Grouping and aggregation.
- Integrating with server-side data sources.
Stay tuned for the next parts of our AG-Grid React series, where we'll delve deeper into these functionalities and more, empowering you to build truly dynamic and data-rich applications. Feel free to experiment with the properties mentioned in the AG-Grid documentation to further customize your grid!