EN
React - how to handle onKeyDown event only when ENTER is pressed on the keyboard?
1
answers
6
points
How do I get the onKeyDown
event handler call the handleKeyDown
function only when ENTER is pressed, not any key on the keyboard?
My code:
// 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 );
1 answer
3
points
Just add a simple if
statement inside handleKeyDown
function, checking if 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 );
1 comments
Add comment
you can check easly event.key codes with https://keycode.info/