Search code examples
reactjsreact-final-form

Update the value on input blur in react-final-form


I'm using react-number-format with react-final-form. My component looks like this:

const CurrencyInput = props => {
  return (
    <NumberFormat
      thousandSeparator=" "
      decimalScale="2"
      isNumericString={true}
      fixedDecimalScale={true}
      allowNegative={false}
      autoComplete="off"
      onBlur={props.input.onBlur}
      onFocus={props.input.onFocus}
      onChange={value => props.input.onChange(value)}
    />
  );
};

react-number-format has allowLeadingZeros prop, which strips leading zeros on input blur. How can I update the value in react-final-form accordingly? If I type zeros before the number, the value in the input itself is corrected on blur, but the value stored by react-final-form stays with zeros.

Here is my codesandbox.


Solution

  • react-number-format does not call onChange after formatting the string.

    But react-number-format has a prop called onValueChange which gets triggered after formatting the string:

    Example: https://codesandbox.io/s/react-final-form-wreact-number-format-bmeg9

    Besides that, I suggest storing the value as a number in state and not as a string.