I\'m trying to implement some very basic key press detection and I can\'t get it to work at all. I have a bare component that should be picking up on the onKeyDown
The DOM wants the element to be focused in order to receive the keyboard event. If you don't want to hack the element with tabIndex
or contentEditable
to get it to focus, you could use native DOM event listeners on window
, and define a different handler in each component that handles keyboard events.
Just be sure to remove the event listener when that component unmounts so all components aren't handling all the time:
componentWillMount: function() {
window.addEventListener('keydown', this.handleKeyDown);
},
componentWillUnmount: function() {
window.removeEventListener('keydown', this.handleKeyDown);
},
Also, there appears to be an npm that provides similar functionality if that's easier: https://www.npmjs.com/package/react-keydown