Sherwood Callaway
Sherwood Callaway

Reputation: 1548

Calling a Component Function After Document-Wide KeyPress (React)

I'm having an issue calling a function within a React component after handling a document-wide key press event. I want to call the move function whenever a directional key is pressed, but I get an error saying it's not a function.

I know this has to do with binding, because when I print "this" within the handleKeyPress method it gives me the document, not the React component. How do I correctly bind the component to move so that I can use it this way?

componentDidMount() {
    document.addEventListener("keydown", this.handleKeyPress, false);
}

handleKeyPress(e) {
  // check if pressed key was a directional key...
  var directionalKey = KEYCODES.indexOf(e.keyCode) == -1 ? false : true;

  // if so, move!
  if (directionalKey) {
    this.move(e.keyCode)
  }

  // but wait, this.move is not a function?
  console.log(this);
}

move(direction) {
  // do something...
}

Thanks!

Upvotes: 0

Views: 434

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

Make sure that the method is invoked with the correct this. Here are a few options.

Using an arrow function.

componentDidMount() {
  document.addEventListener("keydown", e => this.handleKeyPress(e), false);
}

Or manually binding this.

componentDidMount() {
  document.addEventListener("keydown", this.handleKeyPress.bind(this), false);
}

Or if you're using stage-2 or above with Babel, you can use the class properties arrow syntax.

handleKeyPress = (e) => {
  // ...
}

componentDidMount() {
  document.addEventListener("keydown", this.handleKeyPress, false);
}

Upvotes: 1

Related Questions