2

I'm using react-hook-forms to gather localised content, when I set the defaultValues field in the useForm method I might not have all the default values set. For example, it might look like this:

{
  en: {
    first_text: "English first text",
    second_text: "English second text"
  }
}

Note: Adding the default empty values for each field as an empty string for each locale isn't really an option here.

I have created a simplified code sandbox here: https://codesandbox.io/s/react-hook-form-with-multi-locale-pnx11?file=/src/Child.tsx that displays the 2 fields mentioned above and a language switcher.

When I switch the language by clicking the button the issue I encounter is that my input fields (and the formData) get updated with the previous data that was present in the field instead of showing an empty input field.

so:

{
  en: {
    first_text: "English first text",
    second_text: "English second text"
  }
}

becomes:

{
  en: {
    first_text: "English first text",
    second_text: "English second text"
  },
  fr: {
    first_text: "English first text", // instead of ""
    second_text: "English second text" // instead of ""
  }
}

From what I understand the form values get updated when the Controller components get re-rendered but I don't understand why and how I can prevent this. I couldn't find a way to make sure that if I call getValues with a path that doesn't lead to any default value then to render an empty string (or another default value).

Few things I've tried are to pass an empty string as the defaultValue of the Controller components and also to unregister the fields but no success there.

Any advice/help would be highly appreciated!

1 Answer 1

3

Looking at the code I think there's something going on with the initial registration of the form field when the <Controller> tag is first registered within the form. Changing the locale yields a new form data path (name attribute) but I'm not convinced it's getting re-rendered, or at least there's some ref weirdness hanging around internally.

You can force the Controller to re-render (and therefore register a new form input against the new locale path) by adding your form path as a key attribute to the controller tag. This then creates a new instance of that part of the tree and a new form binding in the form hook debugger.

<Controller control={control} name={firstTextId} key={firstTextId} ....

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.