Skip to content

Instantly share code, notes, and snippets.

@mminer
Created September 9, 2016 18:21
Show Gist options
  • Save mminer/abc255772c702582cd199b973dd29e39 to your computer and use it in GitHub Desktop.
Save mminer/abc255772c702582cd199b973dd29e39 to your computer and use it in GitHub Desktop.
Higher order component for React + Recompose allowing components to accept global hotkeys.
// Usage:
//
// const backspace = 8;
//
// export default withHotkeys({
// [backspace]: props => evt => {
// ...
// },
// })(YourComponent);
import React, { Component } from 'react';
import { hoistStatics, wrapDisplayName } from 'recompose';
export default function withHotkeys (handlers, useCapture = false) {
return hoistStatics(BaseComponent =>
class WithHotkeys extends Component {
displayName = wrapDisplayName(BaseComponent, 'withHotkeys');
componentDidMount () {
window.addEventListener('keydown', this.handleKeyDown, useCapture);
}
componentWillUnmount () {
window.removeEventListener('keydown', this.handleKeyDown, useCapture);
}
handleKeyDown = event => {
const handler = handlers[event.keyCode];
if (!handler) {
return;
}
const handlerWithProps = Reflect.apply(handler, this, [this.props]);
if (!handlerWithProps) {
return;
}
event.preventDefault();
event.stopPropagation();
Reflect.apply(handlerWithProps, this, [event]);
};
render () {
return <BaseComponent {...this.props} />;
}
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment