This is a very simple library common to every StackSpot Web project. This is responsible for implementing internationalization and, by default, supports english and portuguese.
This is a very simple library common to every StackSpot Web project. This is responsible for implementing internationalization and, by
default, supports english and portuguese.
1. Get the current language: getLanguage, useLanguage.
2. Change the current language: setLanguage.
3. Get the translations from a dictionary according to the current language: translate, useTranslate.
4. Interpolate a string with variables: interpolate.
tsx
import { useTranslate, interpolate, Dictionary } from '@stack-spot/portal-translate'const MyComponent = ({ username }: { username: string }) => {
const t = useTranslate(dictionary)
const language = useLanguage()
return (
<>
{t.title}
{interpolate(t.hello, username, new Date().toLocaleString(language))}
>
)
}const dictionary = {
en: {
title: 'Main page',
hello: 'Hello $0, today it is $1.',
},
pt: {
title: 'Página principal',
hello: 'Olá $0, hoje é $1.',
},
} satisfies Dictionary
`Multiple language support
To change the language configuration, one can call setupTranslation and specify a new default language and a new list of supported
languages.To just add a new language on top of 'pt' and 'en', call
addLanguageSupport($language) as soon as possible in your application.For declaring Dictionaries with languages other than portuguese and english, specify all languages in a generic:
`ts
const dictionary = {
es: {
hello: 'Hola',
},
fr: {
hello: 'Salut',
},
} satisfies Dictionary<'es' | 'fr'>
`ESDict is a useful type alias for Dictionary<'pt' | 'es' | 'en'>:`ts
const dictionary = {
es: {
hello: 'Hola',
},
pt: {
hello: 'Olá',
},
en: {
hello: 'Hello',
}
} satisfies ESDict
`If a dictionary doesn't contain the translations for the current language, the default language is used (english by default). To change the
default language, call
setupTranslation.When using multi-language support, instead of hardcoding the supported languages, you can use
getSupportedLanguages() and
useSupportedLanguages()` to list all languages that are currently supported.