Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row item on checkbox Selection in React MUI DataGrid

I'm getting Data from API and displaying it using React MUI DataGrid. I have enabled check box selection and I want to get the specific cell items of the selected row and save them in a list.

For Example in the image below, if I click on the checkbox for the 1st row I want to get the "current location" added in a list and then if I click on the 2nd row I want current location of 2nd row added in the existing list.

enter image description here

Below is my current code

<DataGrid
   rows={rows}
   columns={columns}
   checkboxSelection     
   onSelectionModelChange={itm => console.log(itm)}
/>

But I'm getting output like this

enter image description here

I'm very new to React and I'm not sure how to get current Location's value for the selected rows and add it to a list.

like image 664
Maryam Avatar asked Mar 01 '21 15:03

Maryam


People also ask

How do I get selected rows in Mui datagrid?

On the DataGridPro component, you can select multiple rows in two ways: To select multiple independent rows, hold the Ctrl key while selecting rows. To select a range of rows, hold the SHIFT key while selecting rows. To disable multiple row selection, use disableMultipleSelection={true} .

How do I get the selected row data in React?

React Data Grid: Row Selection. Select a row by clicking on it. Selecting a row will remove any previous selection unless you hold down Ctrl while clicking. Selecting a row and holding down Shift while clicking a second row will select the range.

How do I install MUI data grid?

Installation. Using your favorite package manager, install @mui/x-data-grid-pro or @mui/x-data-grid-premium for the commercial version, or @mui/x-data-grid for the free community version. Please note that react >= 17.0.0 and react-dom >= 17.0.0 are peer dependencies.


1 Answers

You can only access the row ids inside onSelectionModelChange callback. If you want to get the whole row objects, use the original rows data and filter the others based on the selected ids.

Note: DataGrid stores each row ID in string internally so if the ID from your original row data is number you may want to convert it toString() before comparing.

rows={rows}
onSelectionModelChange={(ids) => {
  const selectedIDs = new Set(ids);
  const selectedRowData = rows.filter((row) =>
    selectedIDs.has(row.id.toString());
  );
  console.log(selectedRowData);
}}

Live Demo

Edit 66424752/get-row-item-on-checkbox-selection-in-react-material-ui-data-grid

like image 130
NearHuscarl Avatar answered Sep 28 '22 17:09

NearHuscarl