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()
}
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.
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.
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.
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.
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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With