Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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/react@18.2.0/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.18.11/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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading