简体   繁体   中英

Multiple row selection on checkbox and single selection on clicking the row in MUI DataGrid

I'm using MUI DataGrid version 4 component.

What I want are:

  1. to enable multiple selections from the checkbox in the Data Grid (if the user select multiple rows using the checkbox)
  2. to disable multiple selections from the row in the Data Grid (if the user selects multiple rows)
  3. to enable single selection from the row in the Data Grid (if the user selects another row after selecting a row).

But what I get are:

  1. multiple selections from the checkbox are enabled ( what I want )
  2. multiple selections from the row are enabled ( what I don't want ).

For the row selection, I want a single selection only like this answer MUI - Disable multiple row selection in DataGrid but with the multiple selections from the checkbox is enabled.

Here's my code: https://codesandbox.io/s/material-ui-data-grid-selection-vq1ny

Here is the documentation for the selection on the Data Grid component.

Note: it's okay to use DataGridPro component.

Please let me know if the question is not clear.

You can control the selectionModel state and check if the user clicks the cell (not the checkbox). If they click the checkbox, onCellClick won't be fired, if they click other cells, onCellClick will fire, then based on that info to update the selectionModel accordingly:

const cellClickRef = React.useRef(null);
const [selectionModel, setSelectionModel] = React.useState([]);

return (
  <div style={{ height: 400, width: '100%' }}>
    <DataGrid
      checkboxSelection
      selectionModel={selectionModel}
      onCellClick={() => (cellClickRef.current = true)}
      onSelectionModelChange={(selection, detail) => {
        if (cellClickRef.current) {
          if (selection.length > 1) {
            const selectionSet = new Set(selectionModel);
            const result = selection.filter((s) => !selectionSet.has(s));

            setSelectionModel(result);
          } else {
            setSelectionModel(selection);
          }
        } else {
          setSelectionModel(selection);
        }
        cellClickRef.current = null;
      }}
      {...data}
    />
  </div>
);

代码沙盒演示

Related answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM