Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

337
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!