Can I initialize the checkbox selection in MUI DataGrid?

22.2k views Asked by At

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?

3

There are 3 answers

5
NearHuscarl On BEST ANSWER

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

0
Aakash Sharma On
import * as React from "react";
import {
  DataGrid,
  RowData,
  useRows,
  useApiRef,
  GridApi,
} from "@material-ui/data-grid";
import { useDemoData } from "@material-ui/x-grid-data-generator";

let i = 0;
export default function ControlledSelectionGrid() {
  const apiRef = React.useRef(null);
  console.log("apiRef:", apiRef);
  const ObjRef = React.useRef({
      dataRe:{
        columns:[],
        rows:[]
      }
  })

  const counterRef = React.useRef({
    renderCount:0
  })

    // TODO: https://github.com/mui-org/material-ui-x/issues/246
    const [selection, setSelection] = React.useState([]);

  const columns = [
    { field: "id", headerName: "ID", width: 70 },
    { field: "firstName", headerName: "First name", width: 130 },
    { field: "lastName", headerName: "Last name", width: 130 },
    {
      field: "age",
      headerName: "Age",
      type: "number",
      width: 90,
    },
    {
      field: "fullName",
      headerName: "Full name",
      description: "This column has a value getter and is not sortable.",
      sortable: false,
      width: 160,
      valueGetter: (params) =>
        `${params.getValue("firstName") || ""} ${
          params.getValue("lastName") || ""
        }`,
    },
  ];

  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 },
  ];


  

  //console.log('dataRe out:',ObjRef.current.dataRe)
  

  React.useEffect(() => {
    const dataRe = {
      columns,
      rows
    }
    ObjRef.current.dataRe = dataRe
    counterRef.current.renderCount +=1
    console.log('no of render**:',counterRef.current.renderCount)
    console.log('apiRef.current**:',apiRef.current)
    
    //console.log('in useEffect..') 
    const rowModels = apiRef?.current?.getRowModels();
    console.log("rowModels:", rowModels);
    console.log('dataRe',dataRe)
    if (rowModels!=undefined) {
      if(apiRef.current){
        apiRef.current.setRowModels(
          rowModels.map((r) => {
            //console.log("rowModel row:", r);
            r.selected = r.data.age > 40;
            return r;
          })
        );
      }
    }
  },[apiRef.current]);


  return (
    <div style={{ height: 400, width: "100%" }}>
      <DataGrid
        checkboxSelection
        onSelectionChange={(newSelection) => {
          setSelection(newSelection.rows);
        }}
        components={{
          noRowsOverlay: (params) => {
            //console.log('params in noRowsOverlay:',params)
            if (!apiRef.current) {
              //console.log('in apiRef current noRowsOverlay')
              apiRef.current = params.api.current;
              //console.log('apiRef.current in noRowOverlay:',apiRef.current)
            }
            return <div>No rows</div>;
          },
        }}
        {...ObjRef.current.dataRe}
      />
    </div>
  );
}

0
shawnrushefsky On

The DataGrid has a selectionModel property that accepts an array of row IDs.

<DataGrid
  columns={columns}
  rows={rows}
  pageSize={10}
  checkboxSelection
  onSelectionChange={e => console.log(e.rows)}
  selectionModel={[rowId1, rowId2, rowId3]}
/>