Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Redux: What is the canonical way to bind a keypress action to kick off a reducer sequence?

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:

  • React - detect 'enter' key press in change event this one isn't helpful because it just binds to the onChange event of a text area
  • https://facebook.github.io/react/docs/events.html#keyboard-events doesn't tell you how to bind and in fact I really couldnt figure out how to use onKeyDown at all with a element! weird.
like image 609
swyx Avatar asked Feb 05 '23 07:02

swyx


1 Answers

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.

like image 115
just-boris Avatar answered Feb 08 '23 16:02

just-boris