Why does my custom TextField reset to its default value when content is deleted?

455 Views Asked by At

I created a custom FormCurrencyField that uses MUI TextField, react-number-format NumericFormat, and react-hook-form useController.

It works: the values are correctly formatted as currencies and the form model is correctly updated.

The issue I am having with it is that if I delete the content of the TextField, it gets re-set with the default value. I cannot figure out why.

Here is a demo of the issue: https://stackblitz.com/edit/react-odfkwv

2

There are 2 best solutions below

1
todevv On BEST ANSWER

You use defaultValues, this is shown when there is no values. Instead of that use values like so :

const {
    control,
    formState,
    formState: { isValidating },
  } = useForm({
    mode: 'onChange',
    values: { price: 1000 },
  });
1
codejockie On

defaultValues is what the form field should reset to when the field is empty. If you want the behaviour where the field resets to an empty field when content is cleared or deleted, replace defaultValues with values in the useForm options.