Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

350
Vistas
State updating for onkeyup, but not for onclick in React

I am working on an app that uses both onkeyup and onclick events. onkeyup is working as expected, however, onclick is not working as expected. See the code below...

//the state
 const [currentGuess, setCurrentGuess] = useState("");

//the callback function
const handleKeyup = (e) => {
  let pressedKey = "";
  if (typeof e == "string") {
    pressedKey = e;
  }

 const checkPressedKey = pressedKey ? pressedKey : e.key;
 setCurrentGuess((prev) => prev + checkPressedKey);
 console.log(currentGuess.length);
}

//triggering callback when user types on keyboard
 useEffect(() => {
    window.addEventListener("keyup", handleKeyup);

    return () => window.removeEventListener("keyup", handleKeyup);
  }, [handleKeyup]);

//trigger the callback when user types in the fake keyboard
 useEffect(() => {
    setKeyOnClick();
  }, []);

  function setKeyOnClick() {
    const allkey = document.querySelectorAll(".key");

    allkey.forEach((btnKey) => {
      btnKey.addEventListener("click", function () {
        handleKeyup(btnKey.dataset.key);
      });
    });
  }


***for onKeyup**
output: 0, 1, 2, 3, 4 ....

***for onclick**
output: 0 (it doesn't increase);

-HTML-

<button className="key" data-key="Q">Q</button>
<button className="key" data-key="W">W</button>
<button className="key" data-key="E">E</button>
<button className="key" data-key="R">R</button>
<button className="key" data-key="T">T</button>
<button className="key" data-key="Y">Y</button>

As you can see above i have to pass the dataset-key in the handlekeyup function for onclick event.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your buttons have className="key", so if you want to get elements by class name you have to use a dot in querySelectorAll, try this:

const allkey = document.querySelectorAll(".key");

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda