React-i18next: withTranslation HOC looks for translation in first namespace only

Created on 9 Apr 2019  路  4Comments  路  Source: i18next/react-i18next

Not sure whether it's a bug or a question. But I have some problem with withTranslation HOC migrating from react-i18next 7 to 10.

The following code:

withTranslation(['application', 'about'])(AboutControl)

doesn't translate keys anymore if they are not defined in the first namespace (application). nsMode option came to the rescue in old version but it's not available since 10.

All 4 comments

should be enough to change https://github.com/i18next/react-i18next/blob/master/src/useTranslation.js#L41 to

const [t, setT] = useState({ t: i18n.getFixedT(null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0]) });

But honestly having that fallback mode was a bug in the code in first place - it was never meant to have that mode.

So accessing a key in different namespace should out of performance reasons always have been prefixed with namespace explicitly like: t('ns:myKey')

But i guess it could come in handy when not using "keybased" keys but more natural language as keys...if you feel comfortable you can make a PR adding this change including a test case - else i will do so as soon i got time.

@jamuhl, thank you for a quick reply.

Prefixing keys with ns: works fine for me, even when namespaces are omitted:

withTranslation()(AboutControl)

Therefore I still wonder why we should pass namespaces to withTranslation (or useTranslation) without nsMode option. Probably, I misunderstood something.

Anyway, I created a PR as you proposed. Performance is not an issue for us right now so It would be fine if you accept and publish it (we can leave our source code unchanged then). Another minor benefit we can get from nsMode option is that it will be easier to fix translations if namespaces change (withTranslation calls only instead of all t('ns:*') prefixes).

@ezze will review and merge the PR asap. The reason for using withTranslation passing used namespaces has less to do with using them (as you see you can use any namespace prepending ns:). It is about asserting those namespaces / files were loaded before rendering (eg. using xhr backend - or any other async load) and it asserts a rerender on eg. languageChange.

was published in [email protected]

Was this page helpful?
0 / 5 - 0 ratings