blockaj
blockaj

Reputation: 329

How do you do key event handling in React.js?

I'm working on one of my first projects in React.js and have been having some trouble with key event handling. It seems that I'm following examples I've found online pretty precisely. Could some take a look and tell me what they see wrong?

var ScreenplayElement = React.createClass({
    handleKeyPress: function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            console.log("New action to be created");
        }
    },
    render: function () {
        var classString = this.props.type + " screenplay-el";

        return (
        <p className={classString} contentEditable onKeyPress={this.handleKeyPress}><br /></p>
        );
    }
});

Upvotes: 2

Views: 289

Answers (1)

Tom Yates
Tom Yates

Reputation: 931

Try using KeyboardEvent.key (e.key) instead. See the Mozilla Docs.

var ScreenplayElement = React.createClass({
    handleKeyPress: function(e) {
        if (e.key === "Enter") {
            e.preventDefault();
            console.log("New action to be created");
        }
    },
    render: function () {
        var classString = this.props.type + " screenplay-el";

        return (
        <p className={classString} contentEditable onKeyPress={this.handleKeyPress}><br />Content goes in here</p>
        );
    }
});

According to MDN: KeyboardEvent.keyCode is depreceated.

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

Tip: if you place a console.log() message directly before the if statement, it will fire immediately. This way you can determine whether an issue is with the event handler or the if statement :-)

Upvotes: 2

Related Questions