Search code examples
reactjsreact-final-form

How to parse untouched fields in react-final-form


I have an input for an amount in react-final-form. If it's not filled, I need to set its form value to zero. I can't pass an initial value to it as if it hasn't been filled by the user, the input itself should stay empty.

In react-final-form docs there's a parse function. But it works only if the field has been touched (filled and then cleared by the user). Is there any way to parse untouched fields and set them to zero in form values, without updating the input?

Here is my code:

<Field
  name="amount"
  component={CurrencyInput}
  parse={value => (value ? value : 0)}
/> 

And here is the link to my codesandbox.


Solution

  • if by doing this what you are trying to accomplish is that the object displayed in the <pre> has a default value of zero when the input is empty you could use a state variable and inside the parse keep updating its value

      const [amount, setAmount] = useState(0);
      const onInputChange = e => {
        e === "" || e === undefined ? setAmount(0) : setAmount(e);
      };
    

    and in the Field tag

      <Field
        name="amount"
        component={CurrencyInput}
        parse={value => onInputChange(value)}
        defaultValue={amount}
        />
    

    check the codesandbox here:

    https://codesandbox.io/s/react-final-form-wreact-number-format-and-parse-22q3n

    Hope this Resolves the issue