Created
September 9, 2016 18:21
-
-
Save mminer/abc255772c702582cd199b973dd29e39 to your computer and use it in GitHub Desktop.
Higher order component for React + Recompose allowing components to accept global hotkeys.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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