Number with decimal input in React?

<input type="number"
      title="Rate"
      id="rate"
      className="form-control"
      value={this.props.rate}
      min="0.00"
      step="0.001"
      max="1.00"
      presicion={2}   //very important
      onChange={()=>{
        console.log('page rate changed');
        this.props.setrate($('#rate').val());
      }} />

You can do something like this

const floatRegExp = new RegExp('^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$')

const handleValidationOnChange = (e, v, onChange) => {
  const { value } = v
  if (value === '' || floatRegExp.test(value)) {
    onChange(e, v)
  }
}

const InputFloat = props => {
  if (typeof props.onChange !== 'function') {
    return <Form.Input { ...props } />
  }

  const { onChange, ...parentProps } = props

  return <Form.Input
    { ...parentProps }
    onChange={(e, v) => handleValidationOnChange(e, v, onChange)}
  />
}

Form.Input can be any Component that has a value.

You will have to later check for '', that is unavoidable.


    <input
        type="text"
        value={this.props.rate}
        onChange={this.onAmountChange}
      />

type should be text and input value should be defined by regex.

onAmountChange = e => {
    const amount = e.target.value;

    if (!amount || amount.match(/^\d{1,}(\.\d{0,4})?$/)) {
      this.setState(() => ({ amount }));
    }
  };

regex here means: start with a number and add as many as you want. then optionally end with decimal numbers up to 4 decimals.

Tags:

Forms

Reactjs