Gravity supports client-side localisation with the i18next package. The section explains how to translate the client side 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 /src/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 automatically imported and combined, so you can add more JSON files without explicitly importing them anywhere.
/locales
/en
en_dashboard.json
en_help.json
/es
es_dashboard.json
es_help.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, translate dashboard.message.title by keeping the same keys in the English and Spanish dashboard files:
{ "message": { "title": "Welcome to Gravity!" } }
{ "message": { "title": "¡Bienvenido a Gravity!" } }
Adding More Locales
Info
Pro tip – ask ChatGPT to translate the JSON files to new languages.
- Create a new folder inside the
/src/localesdirectory with the locale name eg./frand add your JSON files. - Create its
index.jsusing the existing language folders as a template, import it insrc/app/app.jsxand add it to theresourcessection of the i18nconfig.
import French from 'locales/fr/index'
i18n.use(initReactI18next).init({
resources: {
en: English,
es: Spanish,
fr: French // new language
}
});
Performing Translations
Translations can be performed in three ways:
- Using the
useTranslationhook (available anywhere) - Using
props.t(available in allViewcomponents inside/views) - Using
ViewContext(available anywhere)
import { useTranslation } from 'components/lib';
export function DashboardHeading() {
const { t } = useTranslation();
return <h1>{t('dashboard.title')}</h1>;
}
Table Translations
To translate the table headers, you can pass the a string reference to the translation object to the translation prop of the <Table/>. The JSON object should be named header.
Define header translations under the key supplied to the table. For example, a table with translation="account.billing.invoice" looks up its column labels under account.billing.invoice.header.
<Table data={invoices} translation="account.billing.invoice" />
Switching Languages
There is a language switcher component at the top right of the UI for changing the language. You can add more languages to the locale list in src/settings.json; the user menu maps locales to flags in src/components/user/user.jsx. You will need to import any additional flags you want to use.
import { GB, ES, FR } from 'country-flag-icons/react/3x2'
const flags = { en: GB, es: ES, fr: FR }