I found a strange behaviour when working with input fields with type="number" in React. I have a really simple React component with one controlled number input field and as e.target.value is always a string, I am parsing it to make it a number.
function App() {
const [value, setValue] = React.useState("");
const handleInputChange = (e) => {
const input = e.target.value;
console.log(input);
const parsedValue = parseInt(input, 10);
console.log(parsedValue);
setValue(isNaN(parsedValue) ? input : parsedValue);
};
return (
<form>
<input
type="number"
min={1}
max={100}
value={value}
pattern="\d+"
onChange={handleInputChange}
/>
</form>
);
}
The handleInputChange function is called every time I enter a new value input, but it is not called when I type characters e, '+', or .. For the +, ., and -, I understand that we expect some digit after that so calling onChange doesn't make much sense but for the e, it should have called onChange.
I tried to simulate the same behaviour with vanilla javascript but there change event is only called if I increase/decrease the number using arrow keys. Here is the [codepen example for the same][1]
Can someone explain this behaviour and how can I detect typing e in number input?
Edit:
I think there is some confusion with this question. I want to understand two things about change event behaviour for number input fields.
onChange when I type e, '+', '-', and '.' ?change event is not called when I type some value in input in Vanilla Javascript?
[1]: https://codepen.io/aditya81070/pen/WNjoLaoAny text ending with e is not a number.
It is like 1e3 or 2e4.
So if your number is ending with 1e, it is not valid. Javascript is preventing you from doing so that is why both in your native code and in react, although the onChange(/onchange) is triggered the e.target.value is "". So you can not make use of it.
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