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) {;;

  function handleClick(event) {;;

this is the element :

        <source src={item.url} type="audio/mp3" className="clip" />

my code on codepen :

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}`);;;
  }, []);

  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 or 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.


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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.