Tsabary
Tsabary

Reputation: 3958

OnKeyDown listener called 6 times for every key down

I have added an onKeyDown event listener to the document of my component. It works, but it is called 6-7 times every key down event. It is very basic at this point, all I do is console log the event pretty much, so not sure what is done wrong exactly.

This is my component:

import React, { useEffect } from "react";

const ActionButtons = ({ shuffleClick, keepClick }) => {
  const handleKeyDown = e => {
    console.log(e);
    console.log("this function was called")
  };

  componentDidMount(){

  }

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
  });

  return (
    <div className="flex-group-spaced-around small-margin-top">
      <div className="shuffler__button clickable" onClick={shuffleClick}>
        <p>Shuffle</p>
      </div>

      <div className="shuffler__button clickable" onClick={keepClick}>
        <p>Keep</p>
      </div>
    </div>
  );
};

export default ActionButtons;

Upvotes: 0

Views: 267

Answers (2)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

Your ActionButton component is probably mounted multiple times in your document. This means that for every ActionButton instance an event listener is registered on the document.

Rewrite your event handler to make sure that one a single global event is being listened to.

Upvotes: 1

Corentin de Maupeou
Corentin de Maupeou

Reputation: 100

First, if you use the React Hooks, your "componentDidMount()" should not here. And for your problem, "useEffect" is converting "componentDidMount()" and "componentDidUpdate()". So, may be it's because you don't finish your function, and "componentDidUpdate()" continue that.

Try this :

useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
}, []);

Upvotes: 2

Related Questions