Languages
[Edit]
EN

React - onKeyDown event handler

0 points
Created by:
trincot
360

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:

  • useState hook - to manage the text value as a functional component's state,
  • useRef hook - to assign a reference to input so we can get its value with inputRef.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 );

Alternative titles

  1. React - onKeyDown (functional component)
  2. React - onKeyDown event with specified key
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