Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number input won't take 0 as a value in React app

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.

like image 684
theJuls Avatar asked Oct 15 '25 03:10

theJuls


2 Answers

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.

like image 188
samanime Avatar answered Oct 16 '25 17:10

samanime


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})
like image 41
Kerry Gougeon Avatar answered Oct 16 '25 16:10

Kerry Gougeon