Home > Net >  Why doesn't React.js fire onKey* event handlers for the Escape key?
Why doesn't React.js fire onKey* event handlers for the Escape key?

Time:08-05

Apparently, React doesn't fire onKey* event handlers (such as onKeyDown and onKeyPress) if the key being pressed is Escape and the focus is on an input element. In other words, nothing will be printed on the console when I press the Escape key when the focus is on the input element in this component:

const Input = () => {
  return (
    <input
      type="text"
      value={...}
      onChange={...}
      onKeyDownCapture={(e) => {
        if (e.key === "Escape") {
          console.log("onKeyDownCapture: ", e);
        }
      }}
      onKeyDown={(e) => {
        if (e.key === "Escape") {
          console.log("onKeyDownCapture: ", e);
        }
      }}
      onKeyPress={(e) => {
        if (e.key === "Escape") {
          console.log("onKeyDownCapture: ", e);
        }
      }}
      onKeyUp={(e) => {
        if (e.key === "Escape") {
          console.log("onKeyDownCapture: ", e);
        }
      }}
    />
  );
};

Here is a codesandbox to try it out yourself.

Why is that?

CodePudding user response:

The names of the KeyboardEvent types supported by React's synthetic events are:

onKeyDown onKeyPress onKeyUp

I don't identify the issue that you describe when visiting your CodeSandbox link, but here's an example which demonstrates a single listener which logs the event type and key bound to each of those events, in order for you to experiment/explore and reproduce success in your code:

<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

const logKeyboardEventMeta = (ev) => console.log(ev.type, JSON.stringify(ev.key));

function Input () {
  return (
    <input
      type="text"
      onKeyDown={logKeyboardEventMeta}
      onKeyPress={logKeyboardEventMeta}
      onKeyUp={logKeyboardEventMeta}
    />
  );
}

const reactRoot = ReactDOM.createRoot(document.getElementById('root'));

reactRoot.render(
  <React.StrictMode>
    <Input />
  </React.StrictMode>
);

</script>

  • Related