Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use yup react and developer friendly? #2202

Open
BennyAlex opened this issue Apr 17, 2024 · 2 comments
Open

How to use yup react and developer friendly? #2202

BennyAlex opened this issue Apr 17, 2024 · 2 comments

Comments

@BennyAlex
Copy link

BennyAlex commented Apr 17, 2024

I have a react app built with react-i18n.

I try to change the yup locale depending on the resolved language:

useEffect(() => {
        if (ready) {
            // set document language
            document.documentElement.lang = i18n.resolvedLanguage;
            setLocale(yupLocales[i18n.resolvedLanguage]);
            console.log('BaseRoute: yup locale set to', yupLocales[i18n.resolvedLanguage]);
            setLangSetup(true);
        }
    }, [ready, i18n.resolvedLanguage, setLangSetup]);

All children will only be rendered if langSetup is true, but still I only see the default error messages.

When changing the locale manually at the top of a component it works fine:
yup.setLocale(yupLocales.de);

How do that automatically affecting all components?

@BennyAlex
Copy link
Author

BennyAlex commented Apr 17, 2024

I think the problem is that the schema is defined at the top of the file but not inside the react comonent.

I could move it in there, but then the schema gets recreated every time the component rerenders.

I could also use it with useMemo, but then I have to always import the resolved language to include it in the dependency array, even if it is not required by the component.
Also useMemo comes with a cost.

The other aproach of using t('passwordRequired') for every validation is quite tedious and since yup support dynamic fields in the error message there is no need to set a translation string for every field.

So whats the best aproach for this case?
Best would be having dynamic locales (by opt-in) I guess.

@BennyAlex BennyAlex changed the title How to change the locale globally, not only for the current file? How to use yup react and developer friendly? Apr 17, 2024
@BennyAlex
Copy link
Author

BennyAlex commented Apr 17, 2024

@jquense
Could we have setLocale behave that it will (optionally) reinstanciate the messages?

In my opinion this is the resonable and expected behavior, if you change the language you normally do not want only some parts of your app to be translated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant