DanLeChambre
DanLeChambre

Reputation: 11

Assigning 'onCellKeyDown' handler based on column definition

In MUI X Data Grid, I want to handle the 'onCellKeyDown' event differently for specific column types.

The MUI docs say that to create custom column types we define using the GridColTypeDef type, and then just spread into our column definition like so:

const usdPrice: GridColTypeDef = {
  type: 'number',
  valueFormatter: ({ value }) => valueFormatter.format(Number(value)),
};

<DataGrid
  columns={[
    { field: 'total', ...usdPrice },
  ]}
  rows={rows}
/>

Ideally, I want to introduce something on the column definition to determine whether to override default events. Specifically, to enable use of SHIFT+ENTER for new lines in a multliline input (and prevent that combination starting/stopping edit mode).

Based on how the MUI docs say to introduce custom column types, the solution I have so far is to extend the GridColTypeDef with an additional property, and then use that inside my onCellKeyDown handler like so:

interface CustomGridColTypeDef extends GridColTypeDef { 
  onCellKeyDownFlag?: string;
};

const multiLineCol: CustomGridColTypeDef = {
  onCellKeyDownFlag: 'multiline',
};

const cols = [{field: 'someField', ...multiLineCol}];

const GridComponent = () => {
  const handleMultilineCellKeyDown = (params, event) => {...};

  const handleCellKeyDown = useCallback((params, event) => {
    const {colDef: {onKeyDownFlag}} = params;
    if (onKeyDownFlag === 'multiline') {
      e.preventDefault();
      e.stopPropagation();
      handleMultilineCellKeyDown(params, event);
    }
  },[]);

  return(
    <DataGrid
      columns={cols}
      onCellKeyDown={handleCellKeyDown}
      ...
    />
  );
};

Whilst this appears to be working ok, there does appear to be a bit of lag on input which I think may be because my handleCellKeyDown handler is getting called on every key stroke when typing in the input field?

In any case, I'm starting to wonder whether I'm even approaching the problem in the right way. Am I taking the most performant approach? Or is there a better way to achieve what I'm aiming for?

Upvotes: 1

Views: 1094

Answers (0)

Related Questions