Sometimes, we want to detect Esc key press in React and handle it with JavaScript.
In this article, we’ll look at how to detect Esc key press in React and handle it with JavaScript.
How to detect Esc key press in React and handle it with JavaScript?
To detect Esc key press in React and handle it with JavaScript, we can create our own hook.
For instance, we write
import React, { useEffect } from "react";
const useEscape = (onEscape) => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27) onEscape();
};
window.addEventListener("keydown", handleEsc);
return () => {
window.removeEventListener("keydown", handleEsc);
};
}, []);
};
export default useEscape;
to create the useEscape
hook that listens for the esc key press by listening to the keydown event.
In the handleEsc
event handler, we listen for keyCode
27, which is the esc key press.
We remove the event handler with removeListener
when we unmount the component that uses the hook.
Then we use it in our component by calling useEscape
with a callback that does something when esc is pressed like
const [isOpen, setIsOpen] = useState(false);
useEscape(() => setIsOpen(false));
Conclusion
To detect Esc key press in React and handle it with JavaScript, we can create our own hook.