editableTable

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.9 kB
0
Indexable
Never
import {
  DataGrid,
  GridCellModes,
  GridCellModesModel,
  GridCellParams,
  GridColumns,
  GridRowsProp,
} from '@mui/x-data-grid';
import { SetStateAction, useCallback, useState } from 'react';

const EditableTable = ({
  rows,
  columns,
  height,
  processRowUpdate,
}: {
  rows: GridRowsProp;
  columns: GridColumns;
  height: number;
  processRowUpdate?: any;
}) => {
  const [cellModesModel, setCellModesModel] = useState<GridCellModesModel>({});
  const handleCellClick = useCallback((parameters: GridCellParams) => {
    setCellModesModel((previousModel_: GridCellModesModel) => {
      return {
        ...Object.fromEntries(
          Object.keys(previousModel_).map((id) => [
            id,
            Object.fromEntries(
              Object.keys(previousModel_[id]).map((field) => [field, { mode: GridCellModes.View }]),
            ),
          ]),
        ),
        [parameters.id]: {
          ...Object.fromEntries(
            Object.keys(previousModel_[parameters.id] || {}).map((field) => [
              field,
              { mode: GridCellModes.View },
            ]),
          ),
          [parameters.field]: { mode: GridCellModes.Edit },
        },
      };
    });
  }, []);

  const handleCellModesModelChange = useCallback((newModel: SetStateAction<GridCellModesModel>) => {
    setCellModesModel(newModel);
  }, []);
  return (
    <DataGrid
      sx={{ mb: 3, p: 3 }}
      autoHeight
      disableSelectionOnClick
      rows={rows}
      processRowUpdate={processRowUpdate}
      columns={columns}
      hideFooter
      disableColumnMenu
      rowHeight={height}
      headerHeight={54}
      cellModesModel={cellModesModel}
      onCellModesModelChange={handleCellModesModelChange}
      onCellClick={handleCellClick}
      experimentalFeatures={{ newEditingApi: true }}
    />
  );
};

export default EditableTable;