Skip to content

Instantly share code, notes, and snippets.

@rmdort
Created November 26, 2017 16:27
Show Gist options
  • Select an option

  • Save rmdort/a395a85e81e9a3cf8348641d92f75521 to your computer and use it in GitHub Desktop.

Select an option

Save rmdort/a395a85e81e9a3cf8348641d92f75521 to your computer and use it in GitHub Desktop.
keydown react higher order component
import React from 'react'
import emitter from './../../emitter'
import { compose, lifecycle, withStateHandlers } from 'recompose'
/* Flag to check if events have been attached */
var attached = false
export default function withKeydown (options) {
return (WrappedComponent) => {
return compose(
withStateHandlers(
{
keyCode: null,
},
{
handleKeyDown: (props) => (event) => {
/* Respect options.keyCode */
return {
keyCode: event.which === options.keyCode ? event.which : null
}
},
clearCode: () => () => ({ keyCode: null })
}
),
lifecycle({
componentDidMount () {
if (!attached) initEvents()
attached = true
emitter.on('keydown', (event) => {
this.props.handleKeyDown(event)
/* Clear KeyCode */
setTimeout(this.props.clearCode)
})
}
})
)(WrappedComponent)
}
}
function initEvents () {
document.addEventListener('keydown', (event) => emitter.emit('keydown', event))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment