We use the library i18next for handling internationalization in our application. i18next is an internationalization-framework written in and for JavaScript, providing you with the tools to translate your web application into multiple languages. For detailed information, refer to the official i18next documentation.
Locale detection in our application is handled in the src/utilities/router/i18n.ts
module in the Velocity's shop package. Here's a simplified overview of how this process works:
Once the locale is detected, it's shared via the request, allowing all subsequent processes access to the locale information. This ensures that we have consistent locale data throughout the application during the handling of a specific request.
The translation files for our application are located in the src/locales/
directory. These files contain the actual translations of content that will be displayed in our application.
We've created a helper function, getTranslator
, that provides the correct i18next instance for the detected locale. This function exposes i18next's translation function, t
, which we can use to get the translations for our content.
Here's an example of how you can use the getTranslator
function in a component:
const TranslatedComponent = ({ username }: { username: string }) => {
const t = getTranslator();
return (
<div>
{t('hello')} {username}
</div>
);
};
In this example, t('hello')
is used to fetch the translated text for the key 'hello' from our translations files. The function t
can be used anywhere in your components to translate your content. The key you provide to the t
function should match a key in your translation files.
The translation files located under src/locales/
follow a specific format. Each locale has its file, and inside each file, we define a simple object structure that maps translation keys to their respective translations.
Here's an example for English translations:
{
"hello": "Hello",
"welcome": "Welcome to our application"
}
And for Spanish:
{
"hello": "Hola",
"welcome": "Bienvenido a nuestra aplicación"
}
When you call t('hello')
in your components, i18next will automatically fetch the correct translation based on the active locale. For example, if the active locale is English, t('hello')
will return 'Hello'. If it's Spanish, it'll return 'Hola'.
Ensure your translation keys are descriptive and straightforward, making it clear what they correspond to in your application.
Remember, your translation files should cover all the static texts in your application. Any text that the users will see should be translated and should come from these files. This provides a consistent way to manage your translations and makes it easy to update or add new translations as needed.
Powered by Doctave