Skip to content

Instantly share code, notes, and snippets.

@hypervillain
Last active October 13, 2018 10:49
Show Gist options
  • Save hypervillain/751ef21cbb6a3457f0d6e96878b85d54 to your computer and use it in GitHub Desktop.
Save hypervillain/751ef21cbb6a3457f0d6e96878b85d54 to your computer and use it in GitHub Desktop.
A generic React component that listens to keyboard events
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