Languages

React - how to handle onKeyDown event only when ENTER is pressed on the keyboard?

6 points
Asked by:
FryerTuck
649

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
Answered by:
FryerTuck
649

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
Root-ssh
you can check easly event.key codes with https://keycode.info/
Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join