Home > front end >  Input value not changing on keypress and keyup events
Input value not changing on keypress and keyup events

Time:01-27

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?

CodePudding user response:

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.

CodePudding user response:

You can change like this

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

I guess this will resolve

CodePudding user response:

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

  •  Tags:  
  • Related