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.
- Why React doesn't call
onChangewhen I typee, '+', '-', and '.' ? - Why
changeevent is not called when I type some value in input in Vanilla Javascript? [1]: https://codepen.io/aditya81070/pen/WNjoLao