Skip to content

Instantly share code, notes, and snippets.

@mizchi
Created May 7, 2017 08:51
Show Gist options
  • Save mizchi/2627f2efc6e6d90500f3b5d10a75c369 to your computer and use it in GitHub Desktop.
Save mizchi/2627f2efc6e6d90500f3b5d10a75c369 to your computer and use it in GitHub Desktop.
// Usage:
// <div>
// <GlobalKeyListner keyCode={13} handler={() => console.log('Enter')}/>
// </div>
export default class GlobalKeyListner extends React.Component {
type = 'keydown'
componentDidMount() {
const keyCode = this.props.keyCode
this._bound = (ev: SyntheticEvent) => {
if (ev.keyCode === keyCode) {
this.props.handler(ev)
}
}
window.addEventListener(this.type, this._bound)
}
componentWillUnmount() {
window.removeEventListener(this.type, this._bound)
this._bound = null
}
render() {
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment