Keydown event not working as same as onClick in React


I am trying to trigger a slider next and previous events on

OnClick events are working as expected. But KeyDown handler not working as expected.
It is working fine on first keypress, like incrementing or decrementing by 1.
But after that, it either goes to -1 or +1.

I guess, I am missing some basic concept. Pls guide me where I am missing.

You can test here:
https://codesandbox.io/embed/zen-goodall-35f17?fontsize=14&hidenavigation=1&theme=dark

import React, {useState, useEffect} from "react"

function App(){
  const [curImage, move] = useState(0);

  const handleKeypress = (e) => {
      console.log("keydown", e.keyCode);
      if (e.keyCode === 37) {
          leftClick();
      } else if (e.keyCode === 39) {
          rightClick();
      }
  };

  /* eslint-disable */
  useEffect(() => {
      document.addEventListener("keydown", handleKeypress);
      return () => document.removeEventListener("keydown", handleKeypress);
  }, []);
  /* eslint-enable */

  function leftClick() {
    move(curImage - 1);
}

function rightClick() {
    move(curImage + 1);
}

  return(
    <>
      <button onClick={leftClick}>prev</button>
      {"   "}
      {curImage}
      {"   "}
      <button onClick={rightClick}>next</button>
    </>
  )

}

export default App;

Source: React – Stack Overflow

November 12, 2021
Category : News
Tags: keydown | onclick | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.