Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
Make a React app listen for keyboard input and call a function that has access to state?

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?

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!