0

I've hit a point in my app where I want to dispatch an action with the keycode from any given keypress passed in as a property to the action. I keep getting errors when I'm just trying to console.log the key character.

When I do this:

class DrumMachine extends React.Component {

  componentDidMount() {
    document.addEventListener('keypress', console.log(event.key));
  }

  componentWillUnmount() {
    document.removeEventListener('keypress');
  }

I get the error Uncaught (in promise) DOMException: Failed to load because no supported source was found.

When I try this:

class DrumMachine extends React.Component {

  componentDidMount() {
    document.addEventListener('keypress', drumKeyPress((e) => console.log(e.key)));
  }

  componentWillUnmount() {
    document.removeEventListener('keypress', drumKeyPress());
  }

I get the same error. I'm confident that once I can log the event key I can figure the rest out on my own, but for now I'd just like to understand why what I'm doing isn't working.

Here's a link to the codesandbox if you want to take a gander: https://codesandbox.io/s/k29r3928z7

Editing to address possible duplicate. The linked question has nothing to do with keycodes or React and my question has nothing to do with setTimeout() or playNote functions. Not sure why it was marked as duplicate

Cdhippen
  • 615
  • 1
  • 10
  • 32
  • I need the event handler to be document wide, and trigger anytime a key is pressed with the window open. I can't do that by setting onkeypress properties unless I'm mistaken – Cdhippen Jul 16 '18 at 01:20

1 Answers1

2

You are invoking the console.log right away by writing console.log(event.key). Give a function that can be called when the event happens instead:

document.addEventListener('keypress', (event) => console.log(event.key));
Tholle
  • 108,070
  • 19
  • 198
  • 189