Get the selected values in a datagrid with material ui

Viewed 24230

I have a datagrid with several elements and I would like to retrieve the checked datas. I saw in the element document that there is a controlled selection but I can't get it to work. I'll put my current code below, thanks in advance!

import * as React from 'react';
import { DataGrid } from '@material-ui/data-grid';

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

export default function App() {
    const [select, setSelection] = React.useState([]);
    return (
        <div style={{ height: 400, width: '100%' }}>
            <DataGrid 
                rows={rows} 
                columns={columns}
                pageSize={25}
                checkboxSelection 
                hideFooterPagination 
                onSelectionChange={(newSelection) => {
                    setSelection(newSelection.rows);
                }}
            />
            <h1>{select}</h1>
        </div>
    );
}
5 Answers

If you log your select state you can see that the state is being set according to what is selected. onSelectionChange callback newSelection parameter already contains what you seek.

enter image description here

The main issue with your code is <h1>{select}</h1>. While select is indeed an array and arrays are valid React children, each of your array element contains an object (e.g., firstName, lastName), therefore it won't work with that setup.

enter image description here

You may iterate over the array and print each individual array element object property value.

Example below is printing out firstName:

return (
  <div style={{ height: 400, width: "100%" }}>
    <h1>{select.map((val) => val.firstName)}</h1>
    <DataGrid
      rows={rows}
      columns={columns}
      pageSize={25}
      checkboxSelection
      hideFooterPagination
      onSelectionChange={(newSelection) => {
        setSelection(newSelection.rows);
      }}
    />
  </div>
);

The documentation was updated, and I updated this example: answer from this topic, now according to the documentation selectionModel contains an array of id selected rows

Edit unruffled-hawking-8kez0

I believe you could start by getting total rows onRowSelected, or from the context on some other event method by stepping into the api a bit. This is as of 03/2020, but I found nothing on this in the API docs: onRowSelected={(x) => x.api.current.getSelectedRows()}, on DataGrid "@material-ui/data-grid": "^4.0.0-alpha.22" works for me. I can do everything I need from this in my case.

  <div style={{ height: 400, width: "100%" }}>
    <h1>{select.map((val) => val.firstName)}</h1>
    <DataGrid
      rows={rows}
      columns={columns}
      pageSize={25}
      checkboxSelection
      hideFooterPagination
      onSelectionChange={(newSelection) => {
        setSelection(newSelection.rows);
      }}
    />
  </div>
);

<https://mui.com/components/data-grid/selection/#heading-controlled-selection>

Summarisation of the ans from @95faf8e76605e973 and comment from @abderrezague mohamed for anyone want to copy and paste

return (
  <div style={{ height: 400, width: "100%" }}>
    <h1>{select.map((val) => val.firstName)}</h1>
    <DataGrid
      rows={rows}
      columns={columns}
      pageSize={25}
      checkboxSelection
      hideFooterPagination
      onSelectionModelChange={(newSelectionArray) => {
        // newSelectionArray is [5,1] given the select order is 5 then 1
      }}
    />
  </div>
);
Related