Problem:
I have a controlled input, using Material-UI TextField. I want to have purely numbers, and support type="number" for mobile keyboards, but when having empty string as default, and having a parseInt in the onChange, it will not allow 0 (zero). All other numbers are displayed correctly.
It even correctly sets 0 in the underlying object bound to the TextField.
In other inputs i have default values as empty strings (heavily simplified), like shown:
<TextField
name={"inputToBeSaved"}
value={this.state.objectForSaving.inputToBeSaved|| ''}
onChange={this.handleChange}
variant="outlined"
/>
With corresponding handleChange:
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState(prevState => ({
objectForSaving: {
...prevState.objectForSaving,
[name]: value
}
}))
}
The example above works as espected, but not when trying to work with numbers:
<TextField
type="number"
name={"numberToBeSaved"}
value={this.state.objectForSaving.numberToBeSaved|| ''}
onChange={this.handleChange}
variant="outlined"
/>
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.type === 'number' ? parseInt(target.value) : target.value;
const name = target.name;
this.setState(prevState => ({
objectForSaving: {
...prevState.objectForSaving,
[name]: value
}
}))
}
I know that defaulting to 0, or making it uncontrolled will fix it, but some times I do have values there from the server, so I want to reuse the components.
I have tried to look at this post, but did not find any good solution to keep it controlled: Initializing React number input control with blank value?