Search code examples
javascriptreactjsmaterial-uidatagrid

Differentiate between clicking rows and clicking checboxes in Mui Data Grid


Like the title says - is there a way to differeniate between clicking basically a row and clicking the checkboxes?

enter image description here

I'd would like to be able to select multiple rows but upon clicking in a row - so anywhere other than in the checkbox column - I want to do something else, like call a react hook (open a modal) etc.

Currently I am able to select only by clicking the checkboxes but if I add back onCellClick to open a modal when clicking a row, it also works for the checkbox. So basically I don't want to call onCellClick for the checkbox column ONLY, but for every other column I do.

enter image description here

Thanks!


Solution

  • In onCellClick you can use data.field to see whether or not it is a click of the checkbox column, and if so then ignore that click. Below is a working example.

    import * as React from "react";
    import { DataGrid } from "@mui/x-data-grid";
    import { useDemoData } from "@mui/x-data-grid-generator";
    
    export default function DisableClickSelectionGrid() {
      const { data } = useDemoData({
        dataSet: "Commodity",
        rowLength: 10,
        maxColumns: 6
      });
    
      return (
        <div style={{ height: 400, width: "100%" }}>
          <DataGrid
            checkboxSelection
            disableRowSelectionOnClick
            {...data}
            onCellClick={(data) => {
              if (data.field === "__check__") {
                console.log("ignoring checkbox column");
              } else {
                console.log("Do your main logic here", data);
              }
            }}
          />
        </div>
      );
    }
    

    Edit onCellClick