5

In my React app, I cannot stop propagation of keyboard events from Material UI TextField.

Example of the problem - pressing the backspace key inside the textfield triggers a delete operation in my authoring environment.

On change in the Material UI component:

<TextField onChange={handleChange} />

I try to stop propagation:

const handleChange = event => {
  event.stopPropagation();
  // ...
};

But this does not stop my other event listener from firing:

document.addEventListener("keydown", onKeyDown);

const onKeyDown = event => {
  switch (event.code) {
    case "Backspace":
    case "Delete":
      // ...
      break;
}

Ultimately not a big deal as I can change the scope of my keydown listener from document to the canvas element it's intended to work with, but curious if there was a suggestion here.

Jason Sturges
  • 15,855
  • 14
  • 59
  • 80
  • 1
    I think using `e.nativeEvent.stopImmediatePropagation();` in onKeyDown handler would work but I am not sure TextField exposes that. I think this other question is relevant to yours https://stackoverflow.com/questions/24415631/reactjs-syntheticevent-stoppropagation-only-works-with-react-events – Oleksii Rudenko Dec 06 '19 at 20:19
  • Yep e.nativeEvent.stopImmediatePropagation(); works perfectly! Thanks – Andreu Urruela Jun 20 '20 at 09:20

1 Answers1

0

I had the same problem, I fixed it by adding the following onKeyDown event in TextField Tag.

<TextField onChange={handleChange} onKeyDown={e=>{ e.stopPropagation()}} />
csgeek
  • 711
  • 6
  • 15