Reputation: 4158
I have the following function which I've tied to the onKeyPress event of my ReactJS component:
onKeyPress(e) {
if (!isNumeric(e.key) && e.key !== '.') {
return false;
}
}
This executes properly in that if the input is not numeric (eg. "b"), it will return false. The issue, though, is that the onChange()
event linked to the control is still firing. I would expect that if you suppress the keyboard input, nothing will change and the onChange
event won't fire. That does not appear to be happening.
Upvotes: 0
Views: 965
Reputation: 12874
Just an extension to the number provided by @Joel
onKeyPress(e) {
if (!isNumeric(e.key) && e.key !== '.') {
e.preventDefault();
//return false; Not needed
}
}
You only need e.preventDefault()
, return false
can be excluded
Upvotes: 2
Reputation: 1150
You need to use preventDefault()
on the event as to stop default event bindings. Modify your code to this for the fix:
onKeyPress(e) {
if (!isNumeric(e.key) && e.key !== '.') {
e.preventDefault();
return false;
}
}
Upvotes: 1