Translate days and months globally using react-i18next

1.3k views Asked by At

The user can switch language from Swedish to English or English to Swedish. I can translate all the strings except the days of the week and months.

This is my i18n.js where the main translation utility lives.

import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import XHR from 'i18next-xhr-backend'

// languages
import translationSv from '../locales/sv/translation.json'
import translationEn from '../locales/en/translation.json'

i18n
  .use(XHR)
  .use(LanguageDetector)
  .init({
    debug: false,
    react: {
      useSuspense: false,
    },
    fallbackLng: 'sv',
    keySeparator: false,
    load: 'languageOnly',
    interpolation: {
      escapeValue: false,
    },
    resources: {
      sv: {
        translations: translationSv,
      },
      en: {
        translations: translationEn,
      },
    },
    ns: ['translations'],
    defaultNS: 'translations',
    detection: {
      order: ['querystring', 'localStorage', 'navigator'],
      lookupQuerystring: 'lang',
      lookupLocalStorage: 'i18nextLng',
    },
  })

export default i18n

and in my dateHeader.js, i have the following codes:

import React from 'react'
import moment from 'moment'
import Moment from 'react-moment'


const dateHeader = () => {
<Typography variant="body2">
  <Moment format="DD MMMM" subtract={{ days: 1 }}>
     {dateOfArrival}
  </Moment>
</Typography>
}

I added locale = "sv" in Moment but the days were changed PERMANENTLY to Swedish and I don't want that. I saw that onLanguageChanged can be used to change the language. I am new to this so I am confused on how to translate all days and months globally.

1

There are 1 answers

0
terales On

You can get current language from i18next.language:

import React from 'react'
import moment from 'moment'
import Moment from 'react-moment'

import i18n from './src/i18n.js' // IMPORT YOUR CONFIGURATION

const dateHeader = () => {
<Typography variant="body2">
  <Moment format="DD MMMM" subtract={{ days: 1 }} locale="{{ i18n.language }}">
                                               // ^-- ADD DYNAMIC LOCALE
     {dateOfArrival}
  </Moment>
</Typography>
}