Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

key binding in react.js

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()
}
like image 257
changey Avatar asked Apr 09 '15 23:04

changey


People also ask

What is bind keyword in React?

The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component.

What are key binds?

A key binding is an association between a physical key on a keyboard and a parameter. A parameter can have any number of key bindings associated with it, and a particular key binding can control any number of parameters. Key bindings detects individual keys being pressed.

How do you bind values in React?

Data binding in React can be achieved by using a controlled input . A controlled input is achieved by binding the value to a state variable and a onChange event to change the state as the input value changes.

What is key value in React?

React keys are useful when working with dynamically created components or when your lists are altered by the users. Setting the key value will keep your components uniquely identified after the change.


2 Answers

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

like image 67
changey Avatar answered Oct 10 '22 21:10

changey


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
    }
  }
like image 24
Ashutosh Ranjan Avatar answered Oct 10 '22 21:10

Ashutosh Ranjan