React / Redux and Multilingual (Internationalization) Apps - Architecture

后端 未结 7 1359
挽巷
挽巷 2020-12-04 04:43

I\'m building an app that will need to be available in multiple languages and locales.

My question is not purely technical, but rather about the architecture, and th

7条回答
  •  清歌不尽
    2020-12-04 05:03

    From my experience the best approach is to create an i18n redux state and use it, for many reasons:

    1- This will allow you to pass the initial value from the database, local file or even from a template engine such as EJS or jade

    2- When the user changes the language you can change the whole application language without even refreshing the UI.

    3- When the user changes the language this will also allow you to retrieve the new language from API, local file or even from constants

    4- You can also save other important things with the strings such as timezone, currency, direction (RTL/LTR) and list of available languages

    5- You can define the change language as a normal redux action

    6- You can have your backend and front end strings in one place, for example in my case I use i18n-node for localization and when the user changes the UI language I just do a normal API call and in the backend, I just return i18n.getCatalog(req) this will return all the user strings only for the current language

    My suggestion for the i18n initial state is:

    {
      "language":"ar",
      "availableLanguages":[
        {"code":"en","name": "English"},
        {"code":"ar","name":"عربي"}
      ],
      "catalog":[
         "Hello":"مرحباً",
         "Thank You":"شكراً",
         "You have {count} new messages":"لديك {count} رسائل جديدة"
       ],
      "timezone":"",
      "currency":"",
      "direction":"rtl",
    }
    

    Extra useful modules for i18n:

    1- string-template this will allow you to inject values in between your catalog strings for example:

    import template from "string-template";
    const count = 7;
    //....
    template(i18n.catalog["You have {count} new messages"],{count}) // لديك ٧ رسائل جديدة
    

    2- human-format this module will allow you to converts a number to/from a human readable string, for example:

    import humanFormat from "human-format";
    //...
    humanFormat(1337); // => '1.34 k'
    // you can pass your own translated scale, e.g: humanFormat(1337,MyScale)
    

    3- momentjs the most famous dates and times npm library, you can translate moment but it already has a built-in translation just you need to pass the current state language for example:

    import moment from "moment";
    
    const umoment = moment().locale(i18n.language);
    umoment.format('MMMM Do YYYY, h:mm:ss a'); // أيار مايو ٢ ٢٠١٧، ٥:١٩:٥٥ م
    

    Update (14/06/2019)

    Currently, there are many frameworks implement the same concept using react context API (without redux), I personally recommended I18next

提交回复
热议问题