Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import * as React from 'react'
import { bindActionCreators } from 'redux'
import * as PropTypes from 'prop-types'
import { connect } from 'react-redux'
import InputActions from 'actions/input'
import Section from 'components/common/section'
interface IIndexComponentProps extends React.Props<any> {
keyDown: (key: string) => any
keyUp: (key: string) => any
pressedKeys: { [key: string]: boolean }
}
interface IIndexComponentPassedProps extends React.Props<any> {
message?: string
}
interface IIndexComponentState {
pressedKeys: string[],
}
class IndexComponent extends React.Component<IIndexComponentProps & IIndexComponentPassedProps, IIndexComponentState> {
public static defaultProps = {
message: 'Pressed Keys',
}
public state: { pressedKeys: string[] } = {
pressedKeys: [],
}
public render(): JSX.Element {
return (
<Section title={(<span style={{ color: '#999' }}>KeyUp/KeyDown</span>)} >
{this.props.message}: {this.state.pressedKeys.join(', ')}
</Section>
)
}
private componentDidMount(): void {
document.addEventListener('keydown', event => this.props.keyDown(event.key))
document.addEventListener('keyup', event => this.props.keyUp(event.key))
}
private componentWillReceiveProps(nextProps: IIndexComponentProps): any {
if (nextProps.pressedKeys !== this.props.pressedKeys) {
this.setState({ pressedKeys: Object.keys(nextProps.pressedKeys).filter(key => nextProps.pressedKeys[key]) })
}
}
}
interface IStateToProps {
pressedKeys: { [key: string]: boolean },
}
interface IDispatchToProps {
keyDown: (key: string) => any,
keyUp: (key: string) => any,
}
const mapStateToProps = (state: any) => ({
pressedKeys: state.input.pressedKeys,
})
const mapDispatchToProps = (dispatch: any) => bindActionCreators(
{
keyDown: InputActions.input.key.down,
keyUp: InputActions.input.key.up,
},
dispatch,
)
export default connect<IStateToProps, IDispatchToProps, IIndexComponentPassedProps>(mapStateToProps, mapDispatchToProps)(IndexComponent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment