How to detect 'Enter' key on keyPress when used with React
16,297
Solution 1
Move e.stopPropagataion
from handleSubtotalBy
into handleKeyPress
:
handleKeyPress(event) {
if (event.charCode == 13) {
event.preventDefault();
event.stopPropagation();
this.props.table.handleSubtotalBy(this.props.columnDef, this.state.userInputBuckets);
}
}
handleSubtotalBy(columnDef, partitions) {
const subtotalBy = this.state.subtotalBy || [];
// ...
}
Solution 2
Given answer is not complete,
use
var code = event.keyCode || event.charCode
to support all browser:
Other than this, given answer is correct. Copy that.
Author by
saumj
Updated on June 25, 2022Comments
-
saumj almost 2 years
I am using ReactJs to develop my application. I am trying to submit an input text when Enter is pressed by handling the onKeyPress event. It detects other inputs, but not enter. I have tried different ways -
event.key
,event.charCode
,event.keyCode
,event.which
... Nothing seems to work.React.createElement("input", {tabIndex: "1", onKeyPress: this.handleKeyPress, onChange: this.handleChange, placeholder: "ex: 1,10,15"}), handleChange: function (event) { this.setState({userInputBuckets: event.target.value}); }, handleKeyPress: function (event) { if (event.charCode == 13) { event.preventDefault(); this.props.table.handleSubtotalBy(this.props.columnDef, this.state.userInputBuckets); } },
I also tried with
onKewDown
handling, it detects the correct key, but it doesn't execute the if block even though it evaluatesevent.keyCode == 13
as true. -
saumj almost 7 yearsThanks! That helped.
-
saumj almost 7 yearsFor others who are facing the same problem. Had to use
onKeyDown
instead ofonKeyPress
.