Access local function inside window.onkeydown event

Viewed 65

Trying to call one of my functions inside this window.onkeydown function but I am out of scope. Any ideas what I can do?

componentDidMount() {
  setTimeout(() => {
    window.onkeydown = function(e) {
      if (e.keyCode === 13) {
        console.log("Enter detected");
        // this.handleNextCard(); // this function will throw an error: undefined
      }
    };
  }, 250);
}

componentWillUnmount() {
  window.onkeydown = null;
}

handleFlipCard() {
  this.props.toggleViewAnswer();
}

handleNextCard() {
  this.props.selectNextCard();
}

render(){}
2 Answers

Try using another arrow function for the keydown handler - it'll inherit its this:

window.onkeydown = e => {
  if (e.keyCode === 13) {
    console.log("Enter detected");
    this.handleNextCard();
  }
}

Before arrow functions it could be done this way:

 componentDidMount() {
  setTimeout(() => {
    var that = this;
    window.onkeydown = function(e) {
      if (e.keyCode === 13) {
        console.log("Enter detected");
        that.handleNextCard(); 
      }
    };
  }, 250);
}
Related