Ad

Number With Decimal Input In React?

- 1 answer

I have a number input within a React component, and it needs to accept numbers with a decimal point. Usually, entries will be in the fractions of a cent, like 0.0073, that kind of thing.

<div className="form-group">
  <label htmlFor="rate" className="col-sm-6 control-label">Rate:</label>
  <div className="col-sm-2"> 
    <input type="number"
      title="Rate"
      id="rate"
      className="form-control"
      value={this.props.rate}
      min="0.00"
      step="0.001"
      max="1.00"
      onChange={()=>{
        console.log('page rate changed');
        this.props.setrate($('#rate').val());
      }} />
  </div>
</div>

The issue is that with every keystroke, it's resetting the rate for the app, and then putting that value into the input. So it goes like this:

  • User types 0, the value is set to 0, and 0 is displayed.
  • User types ., 0. isn't a valid number, so the input is cleared.

Can anyone think of a workaround? I know I could just use a normal input, but type="number" leads to some nice stuff in various browsers.

Ad

Answer

I've tried your code and wasn't really affected by your issue, the value is indeed empty when you type the last dot, but the input is not reset.

The thing I changed from your implementation is that I get the input value from the onChange event rather than use jQuery.

<input onChange={e => this.props.setrate(e.target.value)} />

But I doubt your issue comes from that though.

What you could do is not to call your setrate function when you detect an ending dot in your string. Your state will not be modified until the user types a valid number, so one keystroke after the 0..

<input onChange={e => {
  const str = e.target.value
  if (str.charAt(str.length - 1) === '.') { return }
  this.props.setrate(str)
}} />
Ad
source: stackoverflow.com
Ad