Languages

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

6 points
Asked by:
Dirask Community
6810

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:
Dirask Community
6810

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
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