To detect when the user pressed the Enter key when typing in an input field: Add the onKeyDown prop to the input element. Every time the user presses a key in the input field, check if the pressed key is Enter.
Short for Escape, Esc is a key found on the top-left corner of a computer keyboard. It allows the user to abort, cancel, or close an operation. For example, if a web page was loading slow on an Internet browser, pressing the Escape key stops the download.
The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers. To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method.
If you're looking for a document-level key event handling, then binding it during componentDidMount
is the best way (as shown by Brad Colthurst's codepen example):
class ActionPanel extends React.Component {
constructor(props){
super(props);
this.escFunction = this.escFunction.bind(this);
}
escFunction(event){
if(event.keyCode === 27) {
//Do whatever when esc is pressed
}
}
componentDidMount(){
document.addEventListener("keydown", this.escFunction, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.escFunction, false);
}
render(){
return (
<input/>
)
}
}
Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.
EDIT: If you are using hooks, you can use this useEffect
structure to produce a similar effect:
const ActionPanel = (props) => {
const escFunction = useCallback((event) => {
if(event.keyCode === 27) {
//Do whatever when esc is pressed
}
}, []);
useEffect(() => {
document.addEventListener("keydown", escFunction, false);
return () => {
document.removeEventListener("keydown", escFunction, false);
};
}, []);
return (
<input />
)
};
You'll want to listen for escape's keyCode
(27) from the React SyntheticKeyBoardEvent
onKeyDown
:
const EscapeListen = React.createClass({
handleKeyDown: function(e) {
if (e.keyCode === 27) {
console.log('You pressed the escape key!')
}
},
render: function() {
return (
<input type='text'
onKeyDown={this.handleKeyDown} />
)
}
})
Brad Colthurst's CodePen posted in the question's comments is helpful for finding key codes for other keys.
Another way to accomplish this in a functional component, is to use useEffect
, 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(<p>Press ESC to console log "Close"</p>);
}
Instead of console.log, you can use useState
to trigger something.
For a reusable React hook solution
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
Usage:
const [isOpen, setIsOpen] = useState(false);
useEscape(() => setIsOpen(false))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With