How to Get onKeyDown Event to Work With Divs in React
Modern web applications have to listen for events and trigger a function every time a specific browser event occurs to respond to user actions. These functions are called event handlers, and they’re essential for building dynamic applications in React.
onKeyDown
is one of the most useful events in React. It allows developers to keep track of text inputs and dynamically validate their values.
Today’s article will discuss how to handle onKeyDown
events in React.
onKeyDown
Event in React
onKeyDown
is one of the most popular events handling text inputs. This event is triggered every time the user presses down any key while selecting the text input field.
The main difference between onKeyDown
and similar onKeyPress
events is what causes them to trigger. The onKeyDown
event does not differentiate between keys used for typing values (numbers, A-z letters) and others (shift, for example).
onKeyPress
is only triggered for events that produce letters, numbers, or symbols. onKeyDown
is considered a more modern and widely supported event.
It is also more consistent than the onKeyPress
event, regardless of which version of React you are running.
onKeyDown
for Divs in React
Under normal conditions, developers only listen to the onKeyDown
event on text inputs.
<div>
elements are normally wrappers and do not take any input. For this reason, the default behavior of <div>
elements prevents onKeyDown
from working.
Still, there’s no need to worry because a simple fix allows us to use onKeyDown
for <div>
elements. If you want to listen to the onKeyDown
event on a <div>
, you must set the tabIndex
attribute.
This attribute indicates whether or not the <div>
element can be focused. It also deals with the order of elements in the keyboard navigation, using the Tab key.
Here’s an example of a <div>
element that can listen to onKeyDown
event:
class App extends Component {
render() {
return <div tabIndex="0" onKeyDown={() => console.log('key pressed')}>
Some div
</div>;
}
}
You can try out the code yourself on playcode.
Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.
LinkedIn