Handle the onKeyDown event in React

avatar

Borislav Hadzhiev

Sun May 01 20222 min read

Handle the onKeyDown event in React #

To handle the onKeyDown event in React:

  1. Set the onKeyDown prop on the element.
  2. Use the key property on the event object to get the key the user pressed.
  3. For example, if (event.key === 'Enter') {}.
App.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyDown = event => { console.log(event.key); if (event.key === 'Enter') { console.log('✅ Enter key pressed'); } // 👇️ access input value from state // console.log(message); // 👇️ access input value from event object // console.log(event.target.value) }; return ( <div> <input type="text" id="message" name="message" value={message} onKeyDown={handleKeyDown} onChange={event => setMessage(event.target.value)} /> </div> ); }; export default App;

react onkeydown event

If you need to set the onKeyDown event listener on a div element, scroll down to the next code snippet.

We set the onKeyDown prop on the input element, so every time the user presses a button when the input has focus, the handleKeyDown function is invoked.

The key property on the event object returns the value of the key pressed by the user.

Every time the user presses a key, the handleKeyDown function runs and we check if the user pressed Enter.

The condition if (event.key === 'Enter') {} covers all operating systems - Windows, Mac, Linux, Android, etc.

If you need to set the onKeyDown event listener on a div element, set the tabIndex prop on the element to make it focusable.

App.js
const App = () => { const handleKeyDown = event => { console.log('User pressed: ', event.key); }; return ( <div> <div tabIndex={0} onKeyDown={handleKeyDown}> <h2>Some content here</h2> </div> </div> ); }; export default App;

Div elements are not focusable by default, so in order to handle the onKeyDown event on a div, we have to set the tabIndex prop on the element.

The tabIndex attribute indicates that its element can be focused and where it participates in sequential keyboard navigation (using the Tab key).

When an element's tabIndex is set to 0, the element is focusable in sequential keyboard navigation, after any positive tabIndex values.

For example, if other elements on the page have a tab index of 1, 2, 3, etc, an element with a tabIndex of 0 would get focused after the elements with positive tabIndex.

You could also set the element's tabIndex to -1, which means that the element is not reachable via sequential keyboard navigation (using the Tab key), but can be focused with JavaScript or by clicking on it with the mouse.

Use the search field on my Home Page to filter through my more than 1,000 articles.