New to React.
I'm trying to make it so my app is ready to respond to keyboard inputs (namely arrow buttons) from the get-go by setting up an eventListener. Problem seems to be I don't know the right way to add that eventListener so that the function called can access the component's state.
Here's my function
handleKeyUp(event) {
let retRow = this.state.retRow;
let retCol = this.state.retCol;
switch(event.key) {
case 'ArrowUp':
retRow += -1;
break;
case 'ArrowDown':
retRow += 1;
break;
case 'ArrowLeft':
retCol += -1;
break;
case 'ArrowRight':
retCol += 1;
break;
default:
}
this.setState({retRow, retCol});
}
I tried putting it the outermost div of what gets rendered, but this seems to be undefined if I do that.
render() {
/*...*/
return (
<div onKeyUp={this.handleKeyUp}>
<h1>{headerText}</h1>
{this.renderBoard(this.state.rowCount,this.state.colCount)}
<button onClick={() => this.resetGame()}>Restart</button>
</div>
);
}
And I tried putting it on the document when component mounts, but that makes this refer to document
componentDidMount() {
document.addEventListener('keyup', this.handleKeyUp);
}
componentWillUnmount() {
document.removeEventListener('keyup', this.handleKeyUp);
}
}
Either way this is the wrong thing for me to be able to access the component's state with this.state. How can I get my component to respond to keyboard inputs like I want?