Gravity Native supports client-side localisation with the i18n-js package. The section explains how to translate the native UI.
Info
Refer to the server-side localization section to learn how to translate the server-side code.
Locale Files
Locale files are stored inside the /locales folder, and each language has its own folder of .json files. The locales are split to match the same structure as the views.
All .json files inside each locale folder are imported and combined inside the index.js file inside each locale folder. You need to import all of your individual locale files into the index file.
/locales
/en
en_dashboard.json
en_nav.json
/es
es_dashboard.json
es_nav.json
The locale files are simple JSON files containing the strings. The keys are always the same (in English) as these are referenced in the code. The string changes depending on the language.
For example, the English dashboard file contains this structure:
{
"title": "Dashboard",
"message": {
"title": "Welcome to Gravity!",
"text": "Build your next feature here."
}
}
Adding More Locales
Info
Pro tip – ask ChatGPT to translate the JSON files to new languages.
- Create a new folder inside the
/localesdirectory with the locale name eg./frand add your JSON files. - Import the new locale file into the
index.jsfile - Import the locale to
components/app/app.jsand add it to I18n config object.
// locales
import en from '~/locales/en/index';
import es from '~/locales/es/index';
export const i18n = new I18n({ en, es });
Performing Translations
Import the shared i18n instance and render its result in a React Native text component.
import { Text } from 'react-native';
import { i18n } from '~/components/lib';
export function DashboardTitle() {
return <Text>{i18n.t('dashboard.title')}</Text>;
}
Switching Languages
There is a language switcher component in the drawer nav for changing the language. You can add more languages to the dropdown in /components/locale.