Number input is string not integer in React
You can check the type and name of the target
and handle the value accordingly.
For Example
this.setState({
[e.target.name]: e.target.type === 'number' ? parseInt(e.target.value) : e.target.value
});
// or
this.setState({
[e.target.name]: e.target.name === 'price' ? parseFloat(e.target.value) : e.target.value
});
You can use valueAsNumber
property of the Input element
For example:
handleChange(e) {
this.setState({
[e.target.name]: e.target.valueAsNumber || e.target.value
});
}
The e.target.valueAsNumber
will give you the value as number or NaN
if the input is empty.
The || e.target.value
is a fallback in case the valueAsNumber
is NaN.
The parseFloat
in onChange
wont work since 4.
will be parsed as 4
and the user wont be able to type any new digits. Check react-input-number for numeric input in react.