How do I detect Esc keypress on reactjs? The similar thing to jquery
$(document).keyup(function(e) {
if (e.keyCode == 27) { // escape key maps to keycode `
Another way to accomplish this in a functional component, is to use useEffect
and useFunction
, like this:
import React, { useEffect } from 'react';
const App = () => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27) {
console.log('Close')
}
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, []);
return(Press ESC to console log "Close"
);
}
Instead of console.log, you can use useState
to trigger something.