-2
import { useState } from "react";

export default function App() {
  const [height, setHeight] = useState('')

  const handleKeyPressUp = event => {
    const { value } = event.target

    setHeight(value)
  }

  return (
    <input
      value={height}
      onKeyPress={handleKeyPressUp}
      onKeyUp={handleKeyPressUp}
    />
  );
}

I've asked to use keypress instead of onChange to listen the input change. And I use both onKeyPress and onKeyUp because of onKeyPress is triggering right before the input value is changing(How to get text of an input text box during onKeyPress?), and also keypress will only be triggered for keys that produce a character value. i.e it won't be triggered on back space(https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event).

But when assigning the state height value to the input value, the input won't accept any input. Why the input value is not updated on typing text on the field?

Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84
  • 1
    Please use `onChange`, it will work fine. As opposed to a vanilla JS's onchange event, the event will fire during typing. –  Jan 26 '22 at 21:53
  • You're firing for both events, so `keyPress` fires and triggers a render, and your `keyUp` is lost. Keep in mind that react attaches `onChange` to the `input` event. – pilchard Jan 26 '22 at 21:53

3 Answers3

0

Basically OnKeyPress events provide you the "key" which being typed. Using those key you can complete your task.

  const handleKeyPressUp = (event) => {
    const { key } = event;
    let value = height || "";
    if (key === "Backspace") {
      value = value.slice(0, value.length - 1);
    } else {
      value = value + key;
    }
    setHeight(value);
  };

check this link for working solution: https://codesandbox.io/s/nifty-snow-mnrlf?file=/src/App.js:114-389

Note : Above method is kind of hack and need to handle some more corner cases, Using onChange listener is recommended.

Abhilash CR
  • 184
  • 1
  • 4
-1

You can change like this

onChange={(event) => {
  const { value } = event.target;
  setHeight(value)
}}

I guess this will resolve

Omkar Kulkarni
  • 1,091
  • 10
  • 22
-1

On this situation Prefer to use onChange instead of using onkeypress or onkeyup trigger.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 27 '22 at 08:59