Last active
June 12, 2019 18:31
-
-
Save devakone/f5a37b2e55f1789902fa5b95b0e9de4d to your computer and use it in GitHub Desktop.
Reusable hook that takes in a Formik form object and ensures that error messages are translated when the i18next language is changed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect } from 'react'; | |
import { useTranslation } from 'react-i18next'; | |
// When change language is triggered, re-validate the form as to get all errors translated | |
// the parameters here are part of the FormikProps<Values> render props | |
// https://jaredpalmer.com/formik/docs/api/formik#formik-render-methods-and-props | |
const useTranslateFormErrors = (errors, touched, setFieldTouched) => { | |
const { i18n } = useTranslation(); | |
useEffect(() => { | |
i18n.on('languageChanged', lng => { | |
Object.keys(errors).forEach(fieldName => { | |
if (Object.keys(touched).includes(fieldName)) { | |
setFieldTouched(fieldName); | |
} | |
}); | |
}); | |
return () => { | |
i18n.off('languageChanged', lng => {}); | |
}; | |
}, [errors]); | |
}; | |
export default useTranslateFormErrors; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment