React / Redux and Multilingual (Internationalization) Apps - Architecture

后端 未结 7 1362
挽巷
挽巷 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:09

    I would like to propose a simple solution using create-react-app.

    The application will be built for every language separately, therefore whole translation logic will be moved out of the application.

    The web server will serve the correct language automatically, depending on Accept-Language header, or manually by setting a cookie.

    Mostly, we do not change language more than once, if ever at all)

    Translation data put inside same component file, that uses it, along styles, html and code.

    And here we have fully independent component that responsible for its own state, view, translation:

    import React from 'react';
    import {withStyles} from 'material-ui/styles';
    import {languageForm} from './common-language';
    const {REACT_APP_LANGUAGE: LANGUAGE} = process.env;
    export let language; // define and export language if you wish
    class Component extends React.Component {
        render() {
            return (
                

    {language.title}

    {language.description}

    {language.amount}

    ); } } const styles = theme => ({ someStyle: {padding: 10}, }); export default withStyles(styles)(Component); // sets laguage at build time language = ( LANGUAGE === 'ru' ? { // Russian title: 'Транзакции', description: 'Описание', amount: 'Сумма', } : LANGUAGE === 'ee' ? { // Estonian title: 'Tehingud', description: 'Kirjeldus', amount: 'Summa', } : { // default language // English title: 'Transactions', description: 'Description', amount: 'Sum', } );

    Add language environment variable to your package.json

    "start": "REACT_APP_LANGUAGE=ru npm-run-all -p watch-css start-js",
    "build": "REACT_APP_LANGUAGE=ru npm-run-all build-css build-js",
    

    That is it!

    Also my original answer included more monolithic approach with single json file for each translation:

    lang/ru.json

    {"hello": "Привет"}
    

    lib/lang.js

    export default require(`../lang/${process.env.REACT_APP_LANGUAGE}.json`);
    

    src/App.jsx

    import lang from '../lib/lang.js';
    console.log(lang.hello);
    

提交回复
热议问题