Niku1998
Niku1998

Reputation: 165

Material UI - Disable multiple row selection in DataGrid

I want to prevent the Material UI DataGrid multiple checkbox section. When I select the checkbox section, a particular row should be select and the other rows are remain unselected. I tried the disableMultipleSelection option but it would not work.

<DataGrid
  rows={cycle}
  columns={columns}
  pageSize={10}
  checkboxSelection
  disableMultipleSelection
  onRowSelected={({ data, isSelected }) => {
    setDisplay(isSelected);
    setCycleId(data.key);
    setCycleImg(data.storageRef);
  }}
/>          

enter image description here

Upvotes: 15

Views: 22335

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81310

To disable multiple row selection, you have to set checkboxSelection props to false. disableMultipleSelection is only available in DataGridPro, not DataGrid.

<DataGrid
  {...props}
  checkboxSelection={false} // or remove it because it's false by default
/>

If you want both selection checkboxes and single row selection, you may need to control the selection state yourself and remove all but the latest selection when the selection model changes:

const [selectionModel, setSelectionModel] = React.useState<GridRowId[]>([]);

return (
  <div style={{ height: 400, width: '100%' }}>
    <DataGrid
      rows={rows}
      columns={columns}
      pageSize={5}
      checkboxSelection
      selectionModel={selectionModel}
      hideFooterSelectedRowCount
      onSelectionModelChange={(selection) => {
        if (selection.length > 1) {
          const selectionSet = new Set(selectionModel);
          const result = selection.filter((s) => !selectionSet.has(s));

          setSelectionModel(result);
        } else {
          setSelectionModel(selection);
        }
      }}
    />
  </div>
);

Live Demo

V5

Codesandbox Demo

V4

Edit 66828464/material-ui-data-grid

Upvotes: 24

Related Questions