React / Redux and Multilingual (Internationalization) Apps - Architecture

后端 未结 7 1358
挽巷
挽巷 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:21

    Antoine's solution works fine, but have some caveats :

    • It uses the React context directly, which I tend to avoid when already using Redux
    • It imports directly phrases from a file, which can be problematic if you want to fetch needed language at runtime, client-side
    • It does not use any i18n library, which is lightweight, but doesn't give you access to handy translation functionalities like pluralization and interpolation

    That's why we built redux-polyglot on top of both Redux and AirBNB's Polyglot.
    (I'm one of the authors)

    It provides :

    • a reducer to store language and corresponding messages in your Redux store. You can supply both by either :
      • a middleware that you can configure to catch specific action, deduct current language and get/fetch associated messages.
      • direct dispatch of setLanguage(lang, messages)
    • a getP(state) selector that retrieves a P object that exposes 4 methods :
      • t(key): original polyglot T function
      • tc(key): capitalized translation
      • tu(key): upper-cased translation
      • tm(morphism)(key): custom morphed translation
    • a getLocale(state)selector to get current language
    • a translate higher order component to enhance your React components by injecting the p object in props

    Simple usage example :

    dispatch new language :

    import setLanguage from 'redux-polyglot/setLanguage';
    
    store.dispatch(setLanguage('en', {
        common: { hello_world: 'Hello world' } } }
    }));
    

    in component :

    import React, { PropTypes } from 'react';
    import translate from 'redux-polyglot/translate';
    
    const MyComponent = props => (
      
    {props.p.t('common.hello_world')}
    ); MyComponent.propTypes = { p: PropTypes.shape({t: PropTypes.func.isRequired}).isRequired, } export default translate(MyComponent);

    Please tell me if you have any question/suggestion !

提交回复
热议问题