Welcome to the third installment of our AG-Grid React series! In the previous parts, we explored the power and flexibility of AG-Grid and set up our basic React project. Now, it's time to roll up our sleeves and dive into the practical steps of integrating AG-Grid directly into your React application. This post will guide you through the complete setup, from installation to rendering your very first data grid.
Why AG-Grid in React?
Before we begin, it's worth reiterating why AG-Grid is an excellent choice for React developers. It offers:
- High Performance: Capable of handling millions of rows with ease.
- Rich Feature Set: Built-in sorting, filtering, grouping, aggregation, and more.
- Extensibility: Fully customizable with React components for cells, headers, and filters.
- React Integration: A dedicated React component makes integration seamless.
Let's get started with setting it up!
Prerequisites
To follow along with this tutorial, you should have:
- Node.js and npm (or Yarn) installed on your machine.
- A basic understanding of React and JavaScript ES6+.
- A React project set up. If you followed our previous posts, you should have a clean project ready. Otherwise, you can quickly create one using Create React App:
npx create-react-app ag-grid-react-app cd ag-grid-react-app npm start
Step 1: Install AG-Grid Packages
The first step is to install the necessary AG-Grid packages. You'll need two main packages:
ag-grid-community: This is the core AG-Grid library.ag-grid-react: This provides the React wrapper component for AG-Grid.
Open your terminal in your React project directory and run:
npm install ag-grid-community ag-grid-react
Or, if you prefer Yarn:
yarn add ag-grid-community ag-grid-react
Step 2: Import AG-Grid Styles
AG-Grid comes with several pre-built themes that make your grid look professional out-of-the-box. You need to import at least one of these themes along with the core grid styles. For this example, we'll use the ag-theme-alpine theme.
Open your main component file (e.g., src/App.js or src/index.js) and add the following imports:
// In src/App.js or your main component where the grid will be rendered
import 'ag-grid-community/styles/ag-grid.css'; // Core grid CSS
import 'ag-grid-community/styles/ag-theme-alpine.css'; // A built-in theme
You can choose other themes like ag-theme-balham.css, ag-theme-material.css, or ag-theme-quartz.css based on your preference.
Step 3: Create Your First AG-Grid Component
Now, let's integrate the AgGridReact component into your React application. We'll define some sample data and column definitions to display.
Basic Component Structure
Inside your React component (e.g., App.js), you'll import AgGridReact and set up two essential props: rowData and columnDefs.
-
rowData: An array of JavaScript objects, where each object represents a row in your grid, and its properties correspond to the column fields. -
columnDefs: An array of JavaScript objects, where each object defines a column in your grid. Key properties includefield(which maps to a property inrowData) andheaderName(the display name for the column header).
Understanding rowData
rowData is straightforward. Imagine it as an array of records from a database or a list of items you want to display.
const rowData = [
{ 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: 'Audi', model: 'A4', price: 45000 },
];
Defining columnDefs
columnDefs tells AG-Grid how to interpret and display your rowData. Each object in this array defines a single column.
const columnDefs = [
{ field: 'make', headerName: 'Manufacturer' },
{ field: 'model', headerName: 'Model' },
{ field: 'price', headerName: 'Price', valueFormatter: p => '€' + p.value.toLocaleString() },
];
Notice the valueFormatter for the price field. This is an example of how you can customize cell rendering, formatting the price with a Euro symbol and locale-specific thousands separators.
Putting It All Together: A Complete Example
Now, let's combine the imports, data, and column definitions into a single React component.
We'll update the App.js file to render our AG-Grid.
// src/App.js
import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { AgGridReact } from 'ag-grid-react'; // the AG Grid React Component
import 'ag-grid-community/styles/ag-grid.css'; // Core grid CSS
import 'ag-grid-community/styles/ag-theme-alpine.css'; // A built-in theme
function App() {
// Row Data: An array of objects to be displayed as rows in the grid
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: 'Audi', model: 'A4', price: 45000 },
]);
// Column Definitions: Defines the columns to be displayed.
const [columnDefs, setColumnDefs] = useState([
{ field: 'make', headerName: 'Manufacturer', sortable: true, filter: true },
{ field: 'model', headerName: 'Model', sortable: true, filter: true },
{ field: 'price', headerName: 'Price', sortable: true, filter: true, valueFormatter: p => '€' + p.value.toLocaleString() },
]);
// Optional: Default column options for all columns
const defaultColDef = useMemo(() => ({
flex: 1, // Automatically adjust column width to fill available space
minWidth: 100, // Minimum width for columns
resizable: true, // Allow columns to be resized
}), []);
// Grid Options and Callbacks (optional but useful)
const onGridReady = useCallback((params) => {
// You can access the grid API here, e.g., params.api.sizeColumnsToFit();
console.log('Grid is ready!');
}, []);
return (
<div style={{ width: '100%', height: '500px' }} className="ag-theme-alpine">
<AgGridReact
rowData={rowData}
columnDefs={columnDefs}
defaultColDef={defaultColDef}
onGridReady={onGridReady}
/>
</div>
);
}
export default App;
In this complete example:
- We use React's
useStatehook to managerowDataandcolumnDefs. This makes them reactive, meaning the grid will update if these states change. - We've added
sortable: trueandfilter: trueto each column definition, enabling basic sorting and filtering features out of the box. defaultColDefis used to apply common properties to all columns, likeflex: 1for automatic sizing andresizable: true.- The
AgGridReactcomponent is wrapped in a<div>that applies the chosen theme (ag-theme-alpine) and sets a specific width and height. This is crucial for the grid to render correctly. - The
onGridReadycallback is a useful hook that fires when the grid has fully initialized. You can use it to programmatically interact with the grid API.
Sizing Your Grid
For AG-Grid to render correctly, its parent container needs to have defined dimensions. Without a height and width, the grid won't know how big to be and might not appear.
As shown in the example, you can use inline styles or CSS classes:
<div style={{ width: '100%', height: '500px' }} className="ag-theme-alpine">
<AgGridReact
// ... props
/>
</div>
This will make the grid take up 100% of its parent's width and have a fixed height of 500 pixels. Adjust these values to fit your application's layout.
Customizing Themes
Beyond ag-theme-alpine, AG-Grid offers several other built-in themes:
ag-theme-alpine-dark.cssag-theme-balham.cssag-theme-balham-dark.cssag-theme-material.cssag-theme-quartz.cssag-theme-quartz-dark.css
To switch themes, simply change the imported CSS file and update the className on the parent <div>:
// For example, to use the Material theme
import 'ag-grid-community/styles/ag-theme-material.css';
// ... inside your component's return statement
<div style={{ width: '100%', height: '500px' }} className="ag-theme-material">
<AgGridReact
// ... props
/>
</div>
Conclusion
Congratulations! You've successfully set up AG-Grid in your React project, defined your data and columns, and rendered your first interactive data grid. You now have a solid foundation for building complex and powerful data tables.
In the next part of this series, we'll delve deeper into AG-Grid's features, exploring how to enable and configure sorting, filtering, pagination, and more advanced functionalities to make your grid even more dynamic and user-friendly. Stay tuned!