I have an input field of type number
. However, if I try to input 0, it will just ignore it.
What's going on?
Here is roughly my code:
// render part of the component
return {
<div>
<input
type='number'
step='1'
min='0'
max='20'
value={this.state.myTargetsValue}
// @ts-ignore
onFocus={(evt) => evt.target.select()} // This selects all text on the first click
onChange={(evt) => this.handleChange(key, 'myTarget', evt.target.value)}
className='form-control'
/>
</div>
}
Note: the handleChange doesn't make a difference, I removed all code from it for the purpose of testing.
Whenever 0
is acting funny, it generally turns out that its falling into a trap of coming up falsey.
In your handleChange()
function, it's likely you have some code that is trying to do something along these lines:
if (newValue) {
this.setState({ key: newValue });
}
The problem with that is 0
going to fail a check like that. Instead, you'll need to explicitly check the values that aren't good:
if (![null, '', false].includes(newValue)) { }
is one approach. That would check that it isn't one of the other common falsey values. There are other ways, but the basic idea is to make sure it doesn't just default to normal JavaScript behavior.
In react, you will need a state that controls that input. Make a constructor, and cal
this.state={
input:0
}
And your onChange will be something like
e => this.setState({input:e.target.value})
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