Search code examples
reactjsnext.jsnext-i18next

Use i18next translation hook for error messages


So I have a form which works fine and for error messages I have created a schema file which contains errors defined like this

export const dataInputCreateSchema = yupObject({
    company: yup.object().required('This field is required').nullable
  })

In my component I am initializing my i18next translation variable like this const { t } = useTranslation('common'). As to show the error messages in case if user touch the textbox and does not write anything then required field error will be shown and its working like this

const companyFieldError = _.get(errors,'company', '');

_.get is a lodash method that takes in an object, path and default value.

I need to know how I can pass my translation defined in common.json file to companyFieldError? Translation in common.json is something like

"errorMessages": { 
     "requiredField": "This is required Field"
  }

I don't want to discard my schema file but I want to provide key there and that key must get translated. Is there a way to do that?


Solution

  • Here are some changes I will make to support translation of errors.

    1. Use the message in the schema definition.
    export const dataInputCreateSchema = yupObject({
        company: yup.object().required('errorMessages.requiredField').nullable
      })
    
    1. Use the message to get the translated text.
    const message = _.get(errors,'company', '');
    const companyFieldError = t(message);