EN
React - Keyboard Events
0 points
In this article, we would like to show you keyboard events in React.
There are three keyboard events:
- onKeyUp
- onKeyDown
- onKeyPress
In the following example, we create functions that handle onKeyUp
and onKeyDown
events and display to the console which action was performed.
Note:
onKeyPress
event is no longer recommended, so avoid using it.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from "react";
3
// import ReactDOM from "react-dom";
4
5
const App = () => {
6
const handleOnKeyDown = () => {
7
console.log('key is pressed');
8
}
9
const handleOnKeyUp = () => {
10
console.log('key is released');
11
}
12
13
return (
14
<div>
15
<input type="text"
16
onKeyDown={handleOnKeyDown}
17
onKeyUp={handleOnKeyUp}
18
placeholder="press the key"
19
/>
20
</div>
21
);
22
};
23
24
const root = document.querySelector('#root');
25
ReactDOM.render(<App />, root);