EN
React - onKeyDown event handler
0
points
In this article, we would like to show you how to use onKeyDown event handler in React.
Below we present two solutions on how to handle onKeyDown event:
- on any key press,
- on specified key press.
Both of the solutions use:
useStatehook - to manage thetextvalue as a functional component's state,useRefhook - to assign a reference to input so we can get its value withinputRef.current.value(controlled components).
1. onKeyDown on any key press
Below we present handleKeyDown event handler method that sets text value to the input reference current value on any key press.
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 [text, setText] = React.useState('');
const inputRef = React.useRef();
const handleKeyDown = () => {
setText(inputRef.current.value);
};
return (
<div>
<label>Enter text:</label>
<input type="text" ref={inputRef} onKeyDown={handleKeyDown}></input>
<div>{text}</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
2. onKeyDown on specified key press
Below we present handleKeyDown event handler method that sets text value to the input reference current value on Enter key press. Additionally, we pass event as function props, so we can check if the pressed key (event.key) is 'Enter'.
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 [text, setText] = React.useState('');
const inputRef = React.useRef();
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
setText(inputRef.current.value);
}
};
return (
<div>
<label>Enter text:</label>
<input type="text" ref={inputRef} onKeyDown={handleKeyDown}></input>
<div>{text}</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );