Last active
May 30, 2022 08:53
-
-
Save devakone/6605bdf2f634bd5b924e616482508977 to your computer and use it in GitHub Desktop.
This HOC adds the ability to a Formik form to
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
<Formik | |
render={({ handleSubmit, handleChange, handleBlur, setFieldTouched, values, errors, touched }) => ( | |
<WithTranslateFormErrors errors={errors} touched={touched} setFieldTouched={setFieldTouched}> | |
<form onSubmit={handleSubmit}> | |
<input | |
type="text" | |
onChange={handleChange} | |
onBlur={handleBlur} | |
value={values.name} | |
name="name" | |
/> | |
{errors.name && | |
<div> | |
{errors.name} | |
</div>} | |
<button type="submit">Submit</button> | |
</form> | |
</WithTranslateFormErrors> | |
)} | |
/> |
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 PropTypes from 'prop-types'; | |
import React, { useEffect } from 'react'; | |
import { useTranslation } from 'react-i18next'; | |
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]); | |
}; | |
const WithTranslateFormErrors = ({ errors, touched, setFieldTouched, children }) => { | |
useTranslateFormErrors(errors, touched, setFieldTouched); | |
return <>{children}</>; | |
}; | |
WithTranslateFormErrors.propTypes = { | |
form: PropTypes.object | |
}; | |
export default WithTranslateFormErrors; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment