getFixedT not working as expected in react-i18next

29 Views Asked by At

I am trying to use useTranslation inside a react app, and as well I want to refer to a fixed language. the useTranslation t function changes with the browser as expected, but the fixed language always returns english.

The behaviour is demonstrated in this: codesandbox app In this project I get two fixed t functions "en-US" and "fr". Both return the english translations.

In the codesandbox I used:

import { i18n } = useTranslation()

then later

i18n.getFixedT(lng)

I have also used the i18next.getFixedT(lng) and it has the same behaviour.

1

There are 1 best solutions below

0
Bill King On

This is expected behaviour. getFixedT does not load the language if it is not loaded. The recommended approach is to add the language in the init function via tha "preload" property. However if you do not want to preload all the languages on initialization...

The way to do this seems to be to check whether the language has already been loaded:

if (!i18n.hasResourceBundle(lng, "translation")){
    i18n.loadLanguages(lng, (err: unknown) => {
        if (err instanceof Error) {
            console.error("Error loading language: " + err.message)
        } else {
            const newDocT = i18n.getFixedT(lng)
            //.... use newDocT
        }
    })
} else {
    const newDocT = i18n.getFixedT(lng)
    //.... use newDocT
}

Or there is a new feature that allows a language to be passed into useTranslation (but this is a Hook and cannot be used inside useEffect or other Hook)

const { t } = useTranslation('translation', { lng })

You can read about that in issue 1637