React
Using ag-Grid with React: Getting Started

Using the Grid API

Outline

We've now got the ability to select multiple rows of data in our grid. To do something with that data (whether sending it to a server or using it in the UI), we'll need ag-Grid's Grid API. The Grid API lets us progamatically interact with the grid after it's created.

This API comes back to us through a callback on the AgGridReact component, which we can then set as an instance variable on our component.

We'll need to modify our AgGridReact component instance by passing it a new prop called onGridReady along with an inline function to grab that API from the params object it will give us:

// App.js
<AgGridReact
  onGridReady={params => (this.gridApi = params.api)}
   rowSelection="multiple"
   columnDefs={this.state.columnDefs}
   rowData={this.state.rowData}
  ></AgGridReact>

Let's create a button and an accompanying function that will simply alert the selected row data as a string.

First, add the button above our AgGridReact component:

// App.js
<button type="button" onClick={this.onButtonClick}>
    Selected Rows
 </button>

Next, let's add that onButtonClick method to our component class and call the API to get the selected rows with getSelectedNodes:

onButtonClick = () => {
    const selectedNodes = this.gridApi.getSelectedNodes();
    const selectedData = selectedNodes.map(node => node.data);
    const selectedDataString = selectedData
      .map(node => `${node.make} ${node.model}`)
      .join(', ');
    alert(`Selected Nodes: ${selectedDataString}`);
  };

When you run npm start and navigate to localhost:3000, you should be able to select a few rows, click the button, and see an alert that strings that data together. Cool!

The Grid API is insanely powerful! This is just barely scratching the surface of what it can do. You'll definitely want to read through the docs on it to learn more about its full capabilities.

We also have access to a Column API. In the next video, let's use it to toggle the visibility of the Model column.

 

I finished! On to the next chapter