1 year ago

#381973

test-img

Arshdeep Singh Khalsa

Can not change language for schema warning message in i18next

I am using i18next for multilingual support in reactjs. I am also using Yup and defined my schemas in the file below.

    const hasEmail = /^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$/;

    export const validateRequiredEmail = () =>
     yup
    .string()
    .trim()
    .email(i18next.t(MESSAGES.EMAIL_NOT_VALID))
    .required(i18next.t(MESSAGES.EMAIL_REQ))
    .matches(hasEmail, i18next.t(MESSAGES.EMAIL_NOT_VALID));

  export const contactFormSchema = yup.object().shape({
  firstName: yup
    .string()
    .trim()
    .max(16, i18next.t(MESSAGES.FIRST_NAME_LENGTH))
    .required(i18next.t(MESSAGES.FIRST_NAME_REQ)),
  lastName: yup
    .string()
    .trim()
    .max(16, i18next.t(MESSAGES.LAST_NAME_LENGTH))
    .required(i18next.t(MESSAGES.LAST_NAME_REQ)),
  email: validateRequiredEmail(),
  phoneNumber: yup
    .string()
    .trim()
    .min(10, i18next.t(MESSAGES.PHONE_NUMBER_REQ))
    .max(10, i18next.t(MESSAGES.PHONE_NUMBER_REQ))
    .matches(phoneRegExpContactForm, i18next.t(MESSAGES.PHONE_NUMBER_NOT_VALID))
    .required(i18next.t(MESSAGES.PHONE_NUMBER_REQ)),
  message: yup.string().required(i18next.t(MESSAGES.MSG_REQ)),
});

I am facing an issue that whenever I change the language, my schema messages are not changing automatically! Also even after refreshing page they do not change. Sometimes we need to refresh page multiple times to change the schema language after touched is true. Below I am sharing my Formik Input files and i18n file. please help!!

export const FormikInputField = ({ ...props }) => {
  const { t } = useTranslation();
  const [field, meta] = useField(props.name);
  const { touched, error } = { ...meta };

  return (
    <React.Fragment>
      <label
        htmlFor={props.name}
        className="block w-full text-sm sm:text-base font-medium text-gray-700"
      >
        {props.label}
      </label>
      <div className="mt-1 relative">
        <InputField
          touched={touched}
          error={error}
          {...field}
          {...props}
          validation={props.validation}
        />
      </div>
      {props.validation && error ? (
        <span className="text-red-600 mt-2 text-sm">{t(error)}</span>
      ) : (
        <ErrorMessage
          name={props.name}
          component="span"
          className="text-red-600 mt-2 text-sm"
        />
      )}
    </React.Fragment>
  );
};
 

Dropdown.jsx where the button is designed

export default function Dropdown() {
  const { i18n } = useTranslation();
  const [selectedLanguage, setSelectedLanguage] = useState(languages[0]);

  const getLanguageName = (value) => {
    return languages.filter((language) => language.country_code === value);
  };

  const handleLanguageChange = (value) => {
    const getLanguageObject = getLanguageName(value);
    setSelectedLanguage(getLanguageObject[0]);
    i18n.changeLanguage(value);
  };

  useEffect(() => {
    const savedLanguageValue = localStorage.getItem("i18nextLng") || "en-US";
    const languageObject = getLanguageName(savedLanguageValue);
    setSelectedLanguage(languageObject[0]);
  }, []);

return(
 <Menu.Items className="origin-top-right absolute right-0 mt-2 w-32 xl:w-56 rounded-md shadow-lg bg-gray-800 xl:bg-white text-white xl:text-gray-300 ring-1 ring-black ring-opacity-5 divide-y divide-gray-100 focus:outline-none">
          <div className="py-1">
            {languages.map((language) => {
              const { name, country_code, icon } = language;

              return (
                <Menu.Item key={country_code}>
                  {({ active }) => (
                    <span
                      onClick={() => handleLanguageChange(country_code)}
                      className={classNames(
                        active
                          ? "bg-gray-100 text-gray-900 cursor-pointer"
                          : "text-white xl:text-gray-500",
                        "group flex px-4 py-2 text-sm cursor-pointer space-x-3 rtl:space x-reverse"
                      )}
                    >
                      <span className={`fi fi-${icon} px-2 h-5 w-5`}></span>
                      <span>{name}</span>
                    </span>
                  )}
                </Menu.Item>
              );
            })}
          </div>
        </Menu.Items>
);
}

Form file

 <Formik
      initialValues={initialValue}
      validationSchema={contactFormSchema}
      onSubmit={onSubmitHandler}
    >
      {() => {
        return (
          <Form className="space-y-6 ">
            <div>
              <FormikInputField
                type="text"
                name="firstName"
                label={t("First name")}
                // validation={validation}
              />
            </div>
            <div>
              <FormikInputField
                type="text"
                name="lastName"
                label={t("Last name")}
                // validation={validation}
              />
            </div>
            <div>
              <FormikInputField
                type="email"
                name="email"
                label={t("Email")}
                // validation={validation}
              />
            </div>
            <div>
              <FormikInputField
                type="phoneNumber"
                name="phoneNumber"
                label={t("Phone number")}
                // validation={validation}
              />
            </div>
            <div>
              <FormikTextArea
                type="message"
                name="message"
                label={t("Message")}
                // validation={validation}
              />
            </div>
            <div className="flex justify-between ">
              <ConfirmButton
                id="change-password"
                // onMouseDown={() => setValidation(true)}
                loading={loading === true ? "true" : undefined}
                type="submit"
                className=" mt-1 text-sm py-4 px-4 sm:text-lg inline-flex items-center border rounded-md shadow-sm  font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none"
              >
                {t("Submit")}
              </ConfirmButton>
              <CancelButton
                onClick={() => navigate("/")}
                type="button"
                className="ml-3 mt-1 py-4 px-4 text-md inline-flex items-center border rounded-md shadow-sm  font-medium focus:outline-none "
              >
                {t("Cancel")}
              </CancelButton>
            </div>
          </Form>
        );
      }}
    </Formik>

reactjs

internationalization

formik

yup

i18next

0 Answers

Your Answer

Accepted video resources