key binding in react.js

10,693

Solution 1

I ended up binding the keydown event when the component mounted and unmounted:

...

componentDidMount: function() {
  $(document.body).on('keydown', this.handleKeyDown);
},

componentWillUnMount: function() {
  $(document.body).off('keydown', this.handleKeyDown);
},

handleKeyDown: function(event) {
  if (event.keyCode == 13 /*enter*/) {
    this.okAction();
  }
  if (event.keyCode == 27 /*esc*/) {
    this.cancelAction();
  }
},

render: function() {
  return this.state.showDialog ? (
    <div className="dialog" onKeyDown={this.handleKeyDown}>

...

There's probably a better way to do this. The function is used as a part of a dialog component: https://github.com/changey/react-dialog

Solution 2

step 1 : Define it in constructor

  constructor(props) {
    super(props);

    this.state = {        
    }
    this.handleEnterKeyPress = this.handleEnterKeyPress.bind(this)
  }

step 2 : Write it in render method

 render() {   
            return (             
                   <input className ="pageText" type="text" value= "value" onKeyPress = {this.handleEnterKeyPress} />                       
            )
          }

step 3 : write the respective function in the class

handleEnterKeyPress(e) {
    if (e.charCode == 13) {
      // your code
    }
  }
Share:
10,693

Related videos on Youtube

changey
Author by

changey

Updated on September 15, 2022

Comments

  • changey
    changey over 1 year

    was trying to implement key binding in react.js. did some research, but still wondering what's the cleanest way to do it. For example,

    if (event.keyCode == 13 /*enter*/) {
      function()
    }
    if (event.keyCode == 27 /*esc*/) {
      anotherfunction()
    }
    
  • azz0r
    azz0r over 7 years
    Wouldn't advise using jQuery to handle this when you could either use arrow functions to auto bind to handleKeyDown or set the bind up for handleKeyDown in the constructor.