React KeyDown event handler in compnent - function error

Viewed 75

I am creating a web page with ReactJs and I am stuck with one issue. I am trying to handle enter key press in my page using keydown event. Following is piece of code:

class ManageUser extends React.Component {
    componentDidMount() {
      window.addEventListener("keydown", this.keyEventHandler, false);
    }
    keyEventHandler(event: KeyboardEvent) {        
       if (event.keyCode === KEY_CODE.ENTER) {
          this.handlerUserEntry(); //Getting error here....
       }
    }
    handlerUserEntry() {
       console.log('handle user entry here');
    }
}

I am able to capture enter key event. But when I try to call this.handlerUserEntry(); from keyEventHandler function I am getting following error:

TypeError: this.handlerUserEntry is not a function

What am I doing wrong here?

3 Answers

As Florian suggested in their comment, any function references you pass need to be bound to your class, otherwise the this in this.handlerUserEntry will not point to the ManageUser class.

You can do this by adding a constructor with the rest of your code as-is:

class ManageUser extends React.Component {
    ManageUser(props) {
        this.handleUserEntry = this.handleUserEntry.bind(this);
    }
    ...
}

I would avoid using componentDidMount() as its a deprecated feature in React's current docs.

I was able to get a working component with a little help on React Events here.

Below is my working component:

import React from 'react';

class ManageUser extends React.Component {

    handler(event) {
        alert(`
            key: ${event.key}
            keyCode: ${event.keyCode}
            altKey: ${event.altKey}
            ctrlKey: ${event.ctrlKey}
            metaKey: ${event.metaKey}
            shiftKey: ${event.shiftKey}
        `)
    }
    render() {
        return (
            <div style={{display: 'flex', justifyContent: 'center'}}>
                <input
                    placeholder='Hit a key...'
                    onKeyDown={this.handler}
                    onKeyPress={this.handler}
                    onKeyUp={this.handler}
                    />
            </div>
        )
        
    }
}

export default ManageUser

Instead of using custom keydown handler, i started using 'react-keydown' npm package and issue is resolved.

Related