2

Does anybody know how to prevent the delete key to empty the cell content on the react Material-UI Grid?

Today when you click on a cell and hit Delete it deletes its content. I'd like to prevent it from happening.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230

1 Answers1

2

DataGrid will set the cell data to an empty string if you hit Delete or Backspace while not in edit mode. If you don't like that behavior, you can disable it by attaching a keydown handler in the parent element in capture phase and call stopPropagation():

<div
  onKeyDownCapture={(e) => {
    if (e.key === "Backspace" || e.key === "Delete") {
      e.stopPropagation();
    }
  }}
  style={{ height: 400, width: "100%" }}
>
  <DataGrid rows={rows} columns={columns} />
</div>

Live Demo

Edit 67067211/metrial-ui-xgrid-how-to-prevent-delete-key-to-delete-cell-content

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
  • Awesome, I tried the same thing but using onKeyDown instead of onKeyDownCapture but it didn't work! Thanks a lot! – Helio Bentes Apr 14 '21 at 14:51
  • @HelioBentes I forgot to clarify that it should work for `XGrid` too because `DataGrid` and `XGrid` share the same internal components but `DataGrid` has some features disabled for free-tier users. – NearHuscarl Apr 14 '21 at 15:02