Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda