Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save devakone/6605bdf2f634bd5b924e616482508977 to your computer and use it in GitHub Desktop.
Save devakone/6605bdf2f634bd5b924e616482508977 to your computer and use it in GitHub Desktop.
This HOC adds the ability to a Formik form to
<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>
)}
/>
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