Last active
October 13, 2018 10:49
-
-
Save hypervillain/751ef21cbb6a3457f0d6e96878b85d54 to your computer and use it in GitHub Desktop.
A generic React component that listens to keyboard events
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 { Component } from 'react'; | |
import PropTypes from 'prop-types'; | |
/* | |
Example: | |
<KeyListener | |
actions={[ | |
{ | |
keyCode: 27, | |
method: (e) => { | |
console.log('Escape called. Event: ', e); | |
}, | |
}, | |
]} | |
listenerType="keydown" | |
> | |
<Modal /> | |
</KeyListener> | |
*/ | |
class KeyListener extends Component { | |
static propTypes = { | |
actions: PropTypes.arrayOf({ | |
keyCode: PropTypes.string.isRequired, | |
method: PropTypes.func.isRequired, | |
}).isRequired, | |
children: PropTypes.node.isRequired, | |
ComponentWrapper: PropTypes.string || PropTypes.node, | |
listenerType: PropTypes.string.isRequired, | |
} | |
static defaultProps = { | |
ComponentWrapper: 'div', | |
} | |
componentDidMount() { | |
document.addEventListener(this.props.listenerType, this.onKeyEvent, false); | |
} | |
componentWillUnmount() { | |
document.removeEventListener(this.props.listenerType, this.onKeyEvent, false); | |
} | |
onKeyEvent = (event) => { | |
const action = this.props.actions.find(e => e.keyCode === event.keyCode); | |
if (action && action.method) { | |
action.method(event); | |
} | |
} | |
render() { | |
const { | |
ComponentWrapper, | |
children, | |
...rest | |
} = this.props; | |
return ( | |
<ComponentWrapper {...rest}> | |
{children} | |
</ComponentWrapper> | |
); | |
} | |
} | |
KeyListener.displayName = 'KeyListener'; | |
export default KeyListener; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment