Config

loadTranslations

API reference for the loadTranslations() function.

Overview

The loadTranslations function is the primary way to customise translation loading behaviour.

In production, your translations need to be stored so that they can be rendered in your app. By default, your translations will be stored on the GT CDN. You can provide a loadTranslations function to fetch translations from a different source, such as:

  • From your app's bundle (most common)
  • From a database
  • From an API
  • From a different CDN

We provide built-in support for loading translations from local files in your app’s bundle. Follow this guide to set up local translations in your React app.

Reference

Parameters

Prop

Type

Description

TypeDescription
localeThe locale for which translations should be loaded.

Returns

A Promise<any> that resolves to either a string or a JSX object containing the translations for the given locale.


Setup

You must import the loadTranslations function and pass it as a prop to the <GTProvider> component.

src/index.js
import loadTranslations from './loadTranslations';

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <GTProvider locales={['es', 'fr']} loadTranslations={loadTranslations}> // [!code highlight]
      <App />
    </GTProvider>
  </StrictMode>
);

Examples

Load translations from local files

When configured to use local translations, the gtx-cli translate command saves translations to the ./src/_gt directory.

loadTranslations.js
export default async function loadTranslations(locale) {
  const translations = await import(`./_gt/${locale}.json`);
  return translations.default;
};

Load translations from your own CDN

loadTranslations.js
export default async function loadTranslations(locale) {
  try {
    const translations = await fetch(`https://your-cdn.com/translations/${locale}.json`);
    const data = await translations.json();
    return data;
  } catch (e) {
    console.error(e);
    return {};
  }
};

Notes

  • loadTranslations lets you customise how translations are loaded in your app in production.
  • Its most common use case is adding local translations

Next steps

How is this guide?

loadTranslations