React
Using ag-Grid with React: Selection

Checkbox Selection

Outline

Sometimes instead of just wanting users to be able to click on the row itself, we'd rather have them check or uncheck a box to select and deselect a row. This is called checkbox selection and can be configured in ag-Grid with a few different options.

We can first add a checkboxSelection option to the ID column definition:

// App.js
// ID column definition
checkboxSelection: true

Once we enable this, you'll see a checkbox in the ID column that you can use to select and deselect rows.

If you'd like to limit the user to only use the checkbox (and not be able to select by clicking anywhere in the row), you can do that with the suppressRowClickSelection option.

First, add it to our state object:

// App.js
// state object
suppressRowClickSelection: true

Then, add it as a prop to the grid component (you can replace rowMultiSelectWithClick if you'd like):

// App.js
// AgGridReact component props
suppressRowClickSelection={this.state.suppressRowClickSelection}

Now you can only select or deselect rows using the checkbox.

There are a couple of other cool things about the checkbox selection option. First, it can be a function that returns true or false, so you can conditionally decide when to show a checkbox. Second, it can be used in the default column definition.

In the video, we remove the checkboxSelection option from the ID column definition and instead add a function to the defaultColDef object in our state:

// App.js
// defaultColDef object in state
checkboxSelection: function (params) {
  const displayedColumns = params.columnApi.getAllDisplayedColumns();
  return thisIsFirstColumn = displayedColumns[0] === params.column;
},

This function ensures that checkboxes always show in the first column, even if we drag the columns around.

In the next video, we'll learn about header checkbox selection. See you there!

 

I finished! On to the next chapter