Last updated: Apr 6, 2024
Reading timeยท4 min
If you need to detect when the Esc key is pressed, click on the second subheading.
To detect when the Enter key is pressed in React.js:
keydown
event listener to the document
element.Enter
.Enter
.import {useEffect} from 'react'; const App = () => { const myFunction = () => { // Your logic here console.log('pressed Enter โ '); }; useEffect(() => { const keyDownHandler = event => { console.log('User pressed: ', event.key); if (event.key === 'Enter') { event.preventDefault(); // ๐๏ธ Your logic here myFunction(); } }; document.addEventListener('keydown', keyDownHandler); return () => { document.removeEventListener('keydown', keyDownHandler); }; }, []); return ( <div> <h2>Hello world</h2> </div> ); }; export default App;
Enter
key is pressed while the user types in an input
field, scroll down to the next code snippet.We used the useEffect hook to add
a keydown
event listener to the document
element.
Now every time the user presses a key, the keyDownHandler
function is invoked.
In the function, we simply check if the user pressed the Enter
key and if they
did, we call a function.
useEffect
hook is used to clean up the event listener when the component unmounts.I've also written an article on how to submit a form using the Enter key.
To detect when the user pressed the Enter key when typing in an input field:
onKeyDown
prop to the input
element.import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyDown = event => { console.log('User pressed: ', event.key); if (event.key === 'Enter') { // ๐๏ธ Your logic here console.log('Enter key pressed โ '); } }; return ( <div> <input onChange={event => setMessage(event.target.value)} onKeyDown={handleKeyDown} id="message" name="message" /> </div> ); }; export default App;
When the onKeyDown
prop is added to an input
field, we only listen for keys
the user pressed when the
input field is focused.
This is different from the previous code snippet, in which we added the
keydown
event listener on the document
element.
This approach is useful when we need to run some logic when the user has
finished typing and don't want to use a form with an onSubmit
event handler.
You can view the possible keys the user might press by visiting this MDN page.
The condition if (event.key === 'Enter') {}
covers all operating systems -
Windows, Mac, Linux, Android, etc.
If you need to detect when the user presses the Backspace key, click on the following article.
To detect when the Esc key is pressed in React.js:
keydown
event listener to the document
element.Esc
.Escape
.import {useEffect} from 'react'; const App = () => { const myFunction = () => { // Your logic here console.log('pressed Esc โ '); }; useEffect(() => { const keyDownHandler = event => { console.log('User pressed: ', event.key); if (event.key === 'Escape') { event.preventDefault(); // ๐๏ธ Your logic here myFunction(); } }; document.addEventListener('keydown', keyDownHandler); // ๐๏ธ Clean up event listener return () => { document.removeEventListener('keydown', keyDownHandler); }; }, []); return ( <div> <h2>Hello world</h2> </div> ); }; export default App;
We used the useEffect hook to add
a keydown
event listener to the document
element.
Now every time the user presses a key, the keyDownHandler
function is invoked.
The key
property on the KeyboardEvent
object returns the value of the key that was
pressed by the user.
In the function, we simply check if the user pressed the Esc
key and if they
did, we call a function.
The function we returned from the useEffect
hook is used to clean up the event
listener when the component unmounts.
You should always clean up any event listeners you set up to avoid memory leaks in your application.
keydown
event to the document
element, so the event will get triggered as long as the document has focus.This approach can be used to close pop-up menus and modals or run any other custom logic.
You can view the possible keys the user might press by visiting this MDN page.
The condition if (event.key === 'Escape') {}
covers all operating systems -
Windows, Mac, Linux, Android, etc.
If you need to handle the onKeyDown event on a Div element, click on the link and follow the instructions.