reactjsmaterial-uimui-x-data-grid

Can I initialize the checkbox selection in MUI DataGrid?


In a MUI DataGrid it is super easy to add a checkbox selection via the checkboxSelection attribute and listen to selection changes via onSelectionChange:

<DataGrid
  columns={columns}
  rows={rows}
  pageSize={10}
  checkboxSelection
  onSelectionChange={e => console.log(e.rows)}
/>

But is there also a way to initialize the checkbox selection with a set of checked items?


Solution

  • Currently the DataGrid doesn't have a way to set the default selectionModel (something like defaultSelectionModel prop), so in order to set the default selected rows, you need to use controlled mode by adding selectionModel/onSelectionModelChange and pass the initial value in useState. It's an ID array of the rows you wish to select at the start.

    const rows = [
      { id: 1, lastName: "Snow", firstName: "Jon", age: 35 },
      { id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
      { id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
      { id: 4, lastName: "Stark", firstName: "Arya", age: 16 },
      { id: 5, lastName: "Targaryen", firstName: "Daenerys", age: null },
      { id: 6, lastName: "Melisandre", firstName: null, age: 150 },
      { id: 7, lastName: "Clifford", firstName: "Ferrara", age: 44 },
      { id: 8, lastName: "Frances", firstName: "Rossini", age: 36 },
      { id: 9, lastName: "Roxie", firstName: "Harvey", age: 65 }
    ];
    
    function MyDataGrid() {
      const [selectionModel, setSelectionModel] = React.useState(() =>
        rows.filter((r) => r.age > 40).map((r) => r.id),
      );
    
      return (
        <div style={{ height: 400, width: '100%' }}>
          <DataGrid
            checkboxSelection
            rows={rows}
            columns={columns}
            rowSelectionModel={selectionModel}
            onRowSelectionModelChange={setSelectionModel}
          />
        </div>
      );
    }
    

    Live Demo

    Codesandbox Demo