Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

62
Vistas
Input value not changing on keypress and keyup events
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?

7 months ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

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.

7 months ago · Juan Pablo Isaza Denunciar

0

You can change like this

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

I guess this will resolve

7 months ago · Juan Pablo Isaza Denunciar

0

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

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos