I've created a few custom hooks for this approach
This one to refresh error messages inside schema when is changing app language
import { yupResolver } from '@hookform/resolvers/yup';
import { useRouter } from 'next/router';
import { useMemo } from 'react';
const useSchema = (getSchema) => {
const { locale } = useRouter();
const resolver = useMemo(getSchema, [locale]);
return yupResolver(resolver);
};
export default useSchema;
And this one to set global in App component localised error messages
import { useTranslation } from 'react-i18next';
import { setLocale } from 'yup';
export const useLocalisedYupSchema = () => {
const { t } = useTranslation('common');
setLocale({
mixed: {
required: t('validation.required')
},
string: {
min: ({ min }) => t('validation.min', { min }),
max: ({ max }) => t('validation.max', { max })
},
});
};
Also usage of schemas inside component with React Hook Form
import { getChangePasswordSchema } from 'static/schemas/changePassword';
import useSchema from 'utils/hooks/useSchema';
import { useForm } from 'react-hook-form';
const AccountContentSecurity = () => {
...
const resolver = useSchema(getChangePasswordSchema);
const { reset, control, handleSubmit } = useForm({
defaultValues: {
'current_password': '',
'new_password': '',
'password_confirmation': '',
},
resolver,
});
...
and schema
import { passwordSchema } from 'static/schemas';
import { object } from 'yup';
export const getChangePasswordSchema = () => object({
'current_password': passwordSchema,
'new_password': passwordSchema,
'password_confirmation': passwordSchema,
});
i18n
in your example? – Pentaprismi18n
as a prop to schema? Have you tried turning it into function that accepts i18n as an argument and returns yup object? – Aerodyne