i18next / react-i18next

Internationalization for react done right. Using the i18next i18n ecosystem.
https://react.i18next.com
MIT License
9.21k stars 1.02k forks source link

Respect defaultValue in TFunction fallback #1618

Closed tschai-yim closed 1 year ago

tschai-yim commented 1 year ago

🚀 Feature Proposal

Make the fallback TFunction t return the defaultValue if provided like in the actual implementation instead of the key like currently.

If the i18next instance isn't correctly initiated I expect the following to return FooBar not title:

const { t } = useTranslation('someNamespace');
// Returns 'title' instead of 'FooBar'
return t('title', 'FooBar');

Motivation

I encountered this weird unexpected behavior when implementing the top-level error page. If the error propagated too far it also hit the I18nextProvider and suddenly the entire page was only message keys.

Currently, I'm using the following workaround:

import defaultTranslation from './path/to/default/locale.json';

const { t, ready } = useTranslation('error');
function fallbackT(key: keyof typeof defaultTranslation): string {
  return ready ? t(key) : defaultTranslation[key];
}

Example

In error pages but imo would generally make the API more predictable.

adrai commented 1 year ago

Do you see "You will need to pass in an i18next instance by using initReactI18next" in your output? If so, you're lazy loading the translations. We don't want the defaultValue to be returned, instead you need to fix your code! The warning is there so you do something.

tschai-yim commented 1 year ago

I am very aware that ideally an i18next instance should be passed. What I am suggesting is an improvement to your fallback function. If you think this behavior is at all expected and would not improve the predictability and usability of i18n then that's fine. I'll just use the workaround.

Thought I'd just save other people the time of having to find out why a function that can be called does not behave like expected or defined in its types but ig my efforts have been misplaced here.

adrai commented 1 year ago

try v12.2.0 but I really suggest to fix your setup...

tschai-yim commented 1 year ago

Thank you for reconsidering and for the very fast release. Works as expected now 👍

Certainly, if my translation file was more complicated and I already knew how to properly initialize i18n then that would be the better option. Because it's only a single file displayed in rare edge cases and cause next-i18next has so far abstracted the initialization logic for me I'm fine with this workaround of manually importing it.