alperenoz
alperenoz

Reputation: 47

I can't get checked row data with onRowSelected in Material UI DataGrid

I'm trying to get the data of Checked row when it's clicked in DataGrid component.
When I tried to make this , I was able to get this with onRowSelected attribute of DataGrid.

But now I cannot reach this attribute. I don't now is that deprecated or else. Now, with onSelectionModelChange attribute, I can only get the ıd value of that row. But what I need is get the object of that row with fields of it. I can get what ı want with onRowClick attribute, but I have to get it with checkbox selection and ı have to make this with DataGrid component.

Here is my datagrid now

<DataGrid
  rows={this.props.rows}
  columns={this.props.columns}
  pageSize={5}
  checkboxSelection
  disableSelectionOnClick
  onRowSelected={(selection) => {
    //Cannot reach any selection data. Need another attrib. attribute.
    console.log(selection);
  }}
/>

My columns:

columnsPlants: [
  { field: 'plantId', headerName: 'ID', width: 120 },
  { field: 'name', headerName: 'Plant Name', width: 230 },
  { field: 'eic', headerName: 'EIC', width: 170 },
  { field: 'organizationETSOCode', width: 200, headerName: 'Organization ETSO' },
  {
    field: 'addPortfolio',
    headerName: 'Add to Portfolio',
    width: 200,
    editable: false,
    sortable: false,
    disableClickEventBubbling: true,
    renderCell: (params) => {
      return (
        <div
          className="d-flex justify-content-between align-items-center"
          style={{ cursor: 'pointer', marginLeft: '25px' }}
        >
          {this.AddtoPortfolio(params.row.plantId)}
        </div>
      );
    },
  },
],

And the data format I want to get when checkbox selected: enter image description here

Upvotes: 0

Views: 6339

Answers (2)

Ahmed fouad
Ahmed fouad

Reputation: 109

You can only access the row ids inside onSelectionModelChange callback (Edit [onSelectionModelChange] is now [onRowSelectionModelChange]) . 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

Upvotes: 3

hasharnashar
hasharnashar

Reputation: 317

This wasn't working for me until I realised onSelectionModelChange is now onRowSelectionModelChange in MUI DataGrid (using "@mui/x-data-grid": "^6.2.1")

For someone like me who has a hard time deciphering docs before coming to stackoverflow I had to figure this out the hard way i.e. by reading docs

Upvotes: 1

Related Questions