Handling onKeyDown event on Div elements in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
4 min

banner

# Table of Contents

  1. Handling onKeyDown event on Div elements in React
  2. Handle the onKeyDown event in React

# Handling onKeyDown event on Div elements in React

To handle the onKeyDown event on div elements in React:

  1. Set the onKeyDown prop on the div element.
  2. Set the element's tab index to 0, e.g. tabIndex={0}.
  3. Access the pressed key on the event object, e.g. event.key in your handler function.
App.js
const App = () => { const handleKeyDown = event => { console.log('User pressed: ', event.key); }; return ( <div> <div tabIndex={0} onKeyDown={handleKeyDown}> <h2>hello world</h2> </div> </div> ); }; export default App;

react onkeydown div

The code for this article is available on GitHub

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.

# Setting tabIndex to -1

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 using JavaScript or by clicking on it with the mouse.

App.js
const App = () => { const handleKeyDown = event => { console.log('User pressed: ', event.key); }; return ( <div> <div tabIndex={-1} onKeyDown={handleKeyDown}> <h2>hello world</h2> </div> </div> ); }; export default App;

onkeydown tabindex minus one

The code for this article is available on GitHub

With the div's tabIndex set to -1, it can't be focused using the Tab key but it can still be focused with a mouse click (or using JavaScript).

The key property on the KeyboardEvent object returns the value of the key that was pressed by the user.

The keydown event is triggered anytime the user presses a key on their keyboard.

You can view the possible keys the user might press by visiting this MDN page.

# Focusing the element immediately after the page loads

If you want to focus the element on which the onKeyDown prop is set immediately after the page loads, set a ref on the element and call the focus() method in the useEffect hook.

App.js
import {useEffect, useRef} from 'react'; const App = () => { const handleKeyDown = event => { console.log('User pressed: ', event.key); }; const ref = useRef(null); useEffect(() => { ref.current.focus(); }, []); return ( <div> <div ref={ref} tabIndex={-1} onKeyDown={handleKeyDown}> <h2>hello world</h2> </div> </div> ); }; export default App;

focus element on page load

The code for this article is available on GitHub

We used the useRef hook to create a ref object that gives us access to the div element.

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the div element on which we set the ref prop.
App.js
useEffect(() => { ref.current.focus(); }, []);

When we pass a ref prop to an element, e.g. <div ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

We used the focus() method to focus the div in the useEffect hook.

The current property on the ref gives us access to the div element, so calling ref.current.focus() sets the focus on the div.

# Handle the onKeyDown event in React

To handle the onKeyDown event:

  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 the input's value from the state // console.log(message); // 👇️ Access the input's value from the 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

The code for this article is available on GitHub
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.