React
Using ag-Grid with React: Getting Started

Using the Column API

Outline

In the last video, we met the Grid API and got a small taste of what it can do for us. Let's meet its sibling in this video: the Column API. The Column API is similar to the Grid API, but provides methods relevant to columns (like showing, hiding, or resizing them).

Let's create a button to toggle the model column visibility:

<button type="button" onClick={this.toggleModelColumn}>
  Toggle Model Column
</button>

We'll also need to extract our inline function for onGridReady into its method because we'll need to store the instance of both APIs on our class. Modify the use of AgGridReact like this:

<AgGridReact
  onGridReady={this.onGridReady}
  rowSelection="multiple"
  columnDefs={this.state.columnDefs}
   rowData={this.state.rowData}
></AgGridReact>

We'll write the new onGridReady method in just a second.

We're going to toggle the visibility of this column by changing a piece of state and then using React's componentDidUpdate lifecycle method to call ag-Grid's Column API.

To do this, we'll want to add a modelVisbility property to our state object in the constructor:

this.state = {
  modelVisibility: true,
    // ...rest of the state is unchanged
}

Next, let's write our onGridReady function to get both the Column API and the Grid API:

onGridReady = params => {
    this.gridApi = params.api;
    this.columnApi = params.columnApi;
  };

Then, we'll use our button's click handler to call setState and toggle modelVisibility:

toggleModelColumn = () => {
    this.setState({ modelVisibility: !this.state.modelVisibility });
  };

Finally, we'll use componentDidUpdate to call the Column API's setColumnVisible function:

componentDidUpdate() {
  this.columnApi.setColumnVisible('model', this.state.modelVisibility);
}

Great!

The finished App.js file should look like this:

import React, { Component } from 'react';
import './App.css';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-balham.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modelVisibility: true,
      columnDefs: [
        {
          headerName: 'Make',
          field: 'make',
          sortable: true,
          filter: true,
          checkboxSelection: true
        },
        {
          headerName: 'Model',
          field: 'model',
          sortable: true,
          filter: true
        },
        {
          headerName: 'Price',
          field: 'price',
          sortable: true,
          filter: true
        }
      ],
      rowData: []
    };
  }

  componentDidMount() {
    fetch('https://api.myjson.com/bins/15psn9')
      .then(result => result.json())
      .then(rowData => this.setState({ rowData }));
  }

  componentDidUpdate() {
    this.columnApi.setColumnVisible('model', this.state.modelVisibility);
  }

  onGridReady = params => {
    this.gridApi = params.api;
    this.columnApi = params.columnApi;
  };

  toggleModelColumn = () => {
    this.setState({ modelVisibility: !this.state.modelVisibility });
  };

  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}`);
  };

  render() {
    return (
      <div
        className="ag-theme-balham"
        style={{
          height: '500px',
          width: '600px'
        }}
      >
        <button type="button" onClick={this.onButtonClick}>
          Selected Rows
        </button>
        <button type="button" onClick={this.toggleModelColumn}>
          Toggle Model Column
        </button>
        <AgGridReact
          onGridReady={this.onGridReady}
          rowSelection="multiple"
          columnDefs={this.state.columnDefs}
          rowData={this.state.rowData}
        ></AgGridReact>
      </div>
    );
  }
}

export default App;

Run npm start and navigate to localhost:3000. You should be able to click the "Toggle Model Column" to show and hide the column. Awesome!

Just like the Grid API, we've really only scratched the surface of the power of the Column API. Be sure to check out the docs to learn more.

That's the end of the Getting Started guide for ag-Grid Community and React. As always, feel free to reach out to me on Twitter if you need anything. See you in the next tutorial!