Search code examples
javascriptreactjsmaterial-uidatagrid

How to select or deselect a row in a Table using Data Grid Mui


How to select and deselect a row using onclick in @mui/x-data-grid with out the checkboxSelection prop, I am trying to implement selection or deselection of a row in Mui Below is Table Component file

import * as React from "react";
import { v1 } from "uuid";
import {
  DataGrid,
  GridToolbarContainer,
  GridToolbarExport
} from "@mui/x-data-grid";

//css
import css from "./index.module.css";

export default function Table(props) {
  const { tableHeader, data } = props;


  data.forEach((element) => {
    element["id"] = v1();
  });

  function CustomToolbar() {
    return (
      <GridToolbarContainer>
        <GridToolbarExport className={`${css.btn}`} />
      </GridToolbarContainer>
    );
  }

  return (
    <div style={{ height: 350, width: "100%" }}>
      <DataGrid
        className={`${css.root}`}
        rows={data}
        columns={tableHeader}
        pageSize={10}
        rowHeight={30}
        autoPageSize={true}
        disableColumnMenu={true}
        components={{
          Toolbar: CustomToolbar,
        }}
      />
    </div>
  );
}


Solution

  • According to MUI docs, you will need to go through the useDemoData hook in the package @mui/x-data-grid-generator:

    import * as React from 'react';
    import { DataGrid } from '@mui/x-data-grid';
    import { useDemoData } from '@mui/x-data-grid-generator';
    
    export default function SingleRowSelectionGrid() {
      const { data } = useDemoData({
        dataSet: 'Commodity',
        rowLength: 10,
        maxColumns: 6,
      });
    
      return (
        <div style={{ height: 400, width: '100%' }}>
          <DataGrid {...data} />
        </div>
      );
    }
    
    

    In case you would like to unselect a row, simply hold Ctrl and click on it.