This is a newbie question for react-redux I spent a couple hours hunting around before finding so I am posting the question and then answering for posterity and also maybe code review.
I am using react-redux to create a game where I want to use the WASD keys to move a character around a small map. (This is just a practice example for a larger endeavor). The map simply consists of a bunch of colored <div>
s.
As I understand it I need to somehow bind the keypress event to something in the React DOM in order to trigger mapDispatchToProps and then kick off the reevaluation of the reducers. The problem is, this being a keypress, there is nothing to bind to. I am using jquery to bind the keypress and call the function.
Related queries:
You can basically trigger an action in a keypress
event handler
class App extends React.Component {
constructor() {
super();
this.handleKeyPress = this.handleKeyPress.bind(this);
}
handleKeyPress(event) {
// you may also add a filter here to skip keys, that do not have an effect for your app
this.props.keyPressAction(event.keyCode);
}
componentDidMount() {
document.addEventListener('keypress', this.handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener('keypress', this.handleKeyPress);
}
render() {
return <div>Your game content</div>;
}
}
export default connect(mapStateToProps, {keyPressAction})(App)
handleKeyPress
calls the action creator, that will push action down to reducers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With