Created
January 16, 2017 00:56
-
-
Save aboekhoff/e70a8fe5e046f1d74b66f13408505abe to your computer and use it in GitHub Desktop.
This file contains 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
// allows any component to respond to keyboard events | |
// currently only keydown but could be any depending on requirements | |
export default function keyboardable(WrappedComponent) { | |
class KeyboardableComponent extends WrappedComponent { | |
keyboardableOnKeyUp = (e) => { | |
this.onKeyUp(e) | |
} | |
onKeyUp(e) { | |
if (super.onKeyUp) { | |
super.onKeyUp(e) | |
} else if (this.props.onKeyUp) { | |
this.props.onKeyUp(e) | |
} | |
} | |
componentWillMount() { | |
window.addEventListener('keyup', this.keyboardableOnKeyUp) | |
if (super.componentWillMount) { super.componentWillMount() } | |
} | |
componentWillUnmount() { | |
window.removeEventListener('keyup', this.keyboardableOnKeyUp) | |
if (super.componentWillUnmount) { super.componentWillUnmount() } | |
} | |
} | |
return KeyboardableComponent | |
} | |
/* | |
Silly example | |
const KeyboardableDiv = keyboardable(div) | |
class Tile { | |
render() { | |
return ( | |
<div style={ backgroundColor: this.props.backgroundColor }>{this.props.children}</div> | |
) | |
} | |
} | |
const KeyboardableTile = keyboardable(Tile) | |
class Colorful extends React.Component { | |
this.state = { color: 'white' } | |
onKeyUp = (e) => { | |
switch(String.fromCharCode(e.which)) { | |
case 'R': this.setState({ color: 'red' }); break | |
case 'G': this.setState({ color: 'green' }); break | |
case 'B': this.setState({ color: 'blue' }); break | |
case 'W': this.setState({ color: 'white' }); break | |
default: return | |
} | |
} | |
render() { | |
const { color } = this.state | |
return <KeyboardableTile onKeyUp={onKeyUp} /> | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment