How to use a different language in a subtree of a React app? #1715
-
I have a localized React app, and I want a subtree of the app to always use English. But the subtree uses some localized components, so I need a way to display them in English regardless of the global settting. I couldn't find any documentation about this topic. What I tried is essentially this:
In spite of this the subtree keeps using the global language setting. // For use with exclusively English parts of the application.
const engI18n = setupI18n({ locale: 'en', messages: enMessages })
function MyEnglishSubtree {
return (
<I18nProvider i18n={engI18n}>
<MyPage />
</I18nProvider>
)
}
function MyPage(...) {
return (
<AppPage title={t`My Page`}> // Page title is _not_ displayed in English
...
</AppPage>
)
} But to my surprise, if I add a local variable // For use in exclusively English parts of the application.
export const engI18n = setupI18n({ locale: 'en', messages: enMessages })
function MyPage(...) {
const i18n = engI18n
return (
<AppPage title={t`My Page`}> // Page title is displayed in English
...
</AppPage>
)
} How to do it properly, without hacks? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The // For use with exclusively English parts of the application.
const engI18n = setupI18n({ locale: 'en', messages: enMessages })
function MyEnglishSubtree {
return (
<I18nProvider i18n={engI18n}>
<MyPage />
</I18nProvider>
)
}
function MyPage(...) {
const {i18n} = useLingui()
return (
<AppPage title={t(i18n)`My Page`}>
...
</AppPage>
)
} Here is a doc for |
Beta Was this translation helpful? Give feedback.
The
t
macro refers to a global i18n object. To achieve your case you need to use few instances of it, and you actually did. What really should be changed it's just a syntaxHere is a doc for
t
macro https://lingui.dev/ref/macro#t