Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading translations from multiple backends

I have React app using react-i18next, the translations are stored in two locations. One set is stored locally to the app in a folder, the rest of the translations come from a remote API.

I am struggling to have both sets loaded into the app. Using the i18next-chained-backend plugin it seems that it only provides fallbacks if the first backend does not load the translations, i cant seem to configure it to load both sets of translations.

What is the best method of including translations from mulitple sources in a React based app?

like image 772
Rob Holmes Avatar asked Nov 07 '22 20:11

Rob Holmes


1 Answers

I was able to load translations from different places without using any dependency. (Only with npm packages 'react-i18next' and 'i18next')

These are the steps I followed:

  1. In i18n.js, set your client-side locale definitions.
  2. Provide a list of namespaces to look-up translation keys in ns key in the same file.

    Say the namespaces are ['translations', 'bkdynamic']

  3. In your main react component, fetch your translations from an API endpoint.

    In the given sandbox, API call is a mock which fetches sampleTx.json from your public/ directory. This could be replaced to an actual endpoint which returns a JSON.

  4. Using i18next.addResourceBundle API, load these translations for the language you require.

    Load the newly fetched translations in namespace bkdynamic for the selected language. Note: While doing i18next.addResourceBundle call, set deep param to true; so that new translations are extended.

  5. Rest of the translation APIs are same.

Live sandbox here - https://codesandbox.io/embed/i18next-muliple-files-p565v

  • Local translations - 'Hello', 'Morning'
  • Translations loaded from another endpoint - 'Good'

Hope this helps.

like image 147
pritam Avatar answered Nov 15 '22 11:11

pritam