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 `
React uses SyntheticKeyboardEvent to wrap native browser event and this Synthetic event provides named key attribute,
which you can use like this:
handleOnKeyDown = (e) => {
if (['Enter', 'ArrowRight', 'Tab'].includes(e.key)) {
// select item
e.preventDefault();
} else if (e.key === 'ArrowUp') {
// go to top item
e.preventDefault();
} else if (e.key === 'ArrowDown') {
// go to bottom item
e.preventDefault();
} else if (e.key === 'Escape') {
// escape
e.preventDefault();
}
};