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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";
const App = () => {
const handleOnKeyDown = () => {
console.log('key is pressed');
}
const handleOnKeyUp = () => {
console.log('key is released');
}
return (
<div>
<input type="text"
onKeyDown={handleOnKeyDown}
onKeyUp={handleOnKeyUp}
placeholder="press the key"
/>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);