How to work with onKeyPress event in React

Hi again :sweat_smile:

so im working on the drum machine project (alredy passed the test) however my onClick event is working perfectly but onKeyPress doesn’t , when a key is pressed it doesn’t fire and after a click from the mouse a press on any key only repeats the last audio that was clicked by the mouse .
those are my functions :

 function handlePress(event) {
    event.target.firstChild.load();
    event.target.firstChild.play();
    
  }

  function handleClick(event) {
    event.target.firstChild.load();
    event.target.firstChild.play();
}

this is the element :

   <button
      id={item.id}
      className="drum-pad"
      value={item.keyTrigger}
      onClick={handleClick}
      onKeyPress={handlePress}
    >
      <audio>
        <source src={item.url} type="audio/mp3" className="clip" />
      </audio>
      {item.keyTrigger}
    </button>

my code on codepen :
https://codepen.io/3xo13/pen/jOzbgKL?editors=0010

I don’t think you can target buttons with keypress events, as counter-intuitive as that may seem. If you listen to the event at the document level it should register correctly. I referenced the document directly for that; not sure if it’s best practice but it worked for me.

1 Like

you mean by adding event listner ?
i’ve tried the folowing but it didn’t work as well,gave the same results :

const handleKeyPress = useCallback((event) => {
    console.log(`Key pressed: ${event.key}`);
   event.target.firstChild.load();
    event.target.firstChild.play();
  }, []);

  useEffect(() => {
    // attach the event listener
    document.addEventListener('keydown', handleKeyPress);

    // remove the event listener
    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, [handleKeyPress]);
1 Like

Since this is being called by an event listener on the body, there is no event.target.firstChild.load() or event.target.firstChild.play(). The only information you have is the key that was pressed. You need to use that information to figure out which audio element to play. It looks like you have given each audio element and id that corresponds to its key. I’d say that might be something to look into.

2 Likes

that was very helpfull ,i didn’t found the solution yet but i’ll go read about it ,thank you