Created
November 26, 2017 16:27
-
-
Save rmdort/a395a85e81e9a3cf8348641d92f75521 to your computer and use it in GitHub Desktop.
keydown react higher order component
This file contains hidden or 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
| 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