• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

266
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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error