2

I have a simple React component that should play audio via the Web Audio API on keyDown, and stop the audio on keyUp. I have a JSFiddle that shows the same behavior I'm seeing on localhost. Here's the code inline:

var Keyboard = React.createClass({
  componentDidMount: function () {
    var context = new (window.AudioContext || window.webkitAudioContext)();
    var oscillator = context.createOscillator();
    var gain = context.createGain();

    oscillator.type = 'sine';
    oscillator.frequency.value = 3000;
    gain.gain.value = 0.5;

    oscillator.connect(gain);
    gain.connect(context.destination);

    this.setState({
      context: context,
      oscillator: oscillator,
      gain: gain
    });
  },

  render: function() {
    return (
      <div id="keyboard"
           onKeyDown={this.playNote}
           onKeyUp={this.stopNote}>
      </div>
    );
  },

  playNote: function (ev) {
    console.log('play');
    this.state.oscillator.start();
  },

  stopNote: function (ev) {
    console.log('stop');
    this.state.oscillator.stop();
  }
});

React.render(<Keyboard />, document.getElementById('container'));

Even without the Web Audio stuff, I can't get the log statements to show up. I've read the React Event System docs and didn't see anything that would help, and I've written other React components using mouse and change events with no problem -- it seems to be particular to keyboard events. Any help would be greatly appreciated!

Edit: Corrected web audio API call. Should've been start(), not play().

Austin Pocus
  • 993
  • 11
  • 18

2 Answers2

11

A <div> is a container element, not an input element. Keyboard events are only generated by <inputs>, <textarea> and anything with the contentEditable attribute.

You could try

render: function() {
    return (
      <div id="keyboard"
           contentEditable={true}
           onKeyDown={this.playNote}
           onKeyUp={this.stopNote}>
      </div>
    );
}

but this isn't a guaranteed solution.. just a starting point :)

Alex McMillan
  • 17,096
  • 12
  • 55
  • 88
  • Thank you so much! Using an input works, as does the contentEditable fix you suggested. I assumed I'd be able to use keyboard events on any element, not just inputs -- good to know. :) I'll accept your answer as soon as the time limit has passed. – Austin Pocus Jun 05 '15 at 23:21
  • This works, but causes React v15.4.1. to flag a warning:Warning: A component is `contentEditable` and contains `children` managed by React.....Also it prints the key pressed in the div so you need to handle that as well... – NullPumpkinException Feb 05 '17 at 21:16
  • @DataMania `contentEditable` means that the user can enter content directly into the DOM node. If you are *also* rendering child nodes inside the node, the user-entered content will replace these. That warning appears so you can double-check your logic, and will not appear for the example in this answer. With the printing of the key in the `div` - that is the behaviour expected when using `contentEditable`. – Alex McMillan Feb 06 '17 at 20:01
  • @Alex - Thanks for detail. – NullPumpkinException Feb 06 '17 at 20:31
  • 1
    The correct answer or at least a better approach can be find here https://stackoverflow.com/questions/43503964/onkeydown-event-not-working-on-divs-in-react – ncubica Jul 20 '17 at 05:11
6

I just had this problem and found two solutions:

Direct

As mentioned in a similar SO question "onKeyDown event not working on divs in React" (and also in the comments by ncubica), include tabIndex="0", for instance:

<div 
  id="keyboard"
  tabIndex="0" 
  onKeyDown={this.playNote}
  onKeyUp={this.stopNote}>
</div>

Work-around

Just add a vanillaJS eventListener() to your componentWillMount() lifecycle and that will load the event listener whenever your page renders (details here: Adding Lifecycle Methods to a Class)

document.addEventListener("keydown", this.playNote);
document.addEventListener("keyup", this.stopNote);
PhysRex
  • 184
  • 2
  • 7