Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React / Redux and Multilingual (Internationalization) Apps - Architecture

After trying quite a few solutions, I think I found one that works well and should be an idiomatic solution for React 0.14 (i.e. it doesn't use mixins, but Higher Order Components) (edit: also perfectly fine with React 15 of course!).

So here the solution, starting by the bottom (the individual components):

The Component

The only thing your component would need (by convention), is a strings props. It should be an object containing the various strings your Component needs, but really the shape of it is up to you.

It does contain the default translations, so you can use the component somewhere else without the need to provide any translation (it would work out of the box with the default language, english in this example)

import { default as React, PropTypes } from 'react';
import translate from './translate';

class MyComponent extends React.Component {
    render() {

        return (
             <div>
                { this.props.strings.someTranslatedText }
             </div>
        );
    }
}

MyComponent.propTypes = {
    strings: PropTypes.object
};

MyComponent.defaultProps = {
     strings: {
         someTranslatedText: 'Hello World'
    }
};

export default translate('MyComponent')(MyComponent);

The Higher Order Component

On the previous snippet, you might have noticed this on the last line: translate('MyComponent')(MyComponent)

translate in this case is a Higher Order Component that wraps your component, and provide some extra functionality (this construction replaces the mixins of previous versions of React).

The first argument is a key that will be used to lookup the translations in the translation file (I used the name of the component here, but it could be anything). The second one (notice that the function is curryed, to allow ES7 decorators) is the Component itself to wrap.

Here is the code for the translate component:

import { default as React } from 'react';
import en from '../i18n/en';
import fr from '../i18n/fr';

const languages = {
    en,
    fr
};

export default function translate(key) {
    return Component => {
        class TranslationComponent extends React.Component {
            render() {
                console.log('current language: ', this.context.currentLanguage);
                var strings = languages[this.context.currentLanguage][key];
                return <Component {...this.props} {...this.state} strings={strings} />;
            }
        }

        TranslationComponent.contextTypes = {
            currentLanguage: React.PropTypes.string
        };

        return TranslationComponent;
    };
}

It's not magic: it will just read the current language from the context (and that context doesn't bleed all over the code base, just used here in this wrapper), and then get the relevant strings object from loaded files. This piece of logic is quite naïve in this example, could be done the way you want really.

The important piece is that it takes the current language from the context and convert that into strings, given the key provided.

At the very top of the hierarchy

On the root component, you just need to set the current language from your current state. The following example is using Redux as the Flux-like implementation, but it can easily be converted using any other framework/pattern/library.

import { default as React, PropTypes } from 'react';
import Menu from '../components/Menu';
import { connect } from 'react-redux';
import { changeLanguage } from '../state/lang';

class App extends React.Component {
    render() {
        return (
            <div>
                <Menu onLanguageChange={this.props.changeLanguage}/>
                <div className="">
                    {this.props.children}
                </div>

            </div>

        );
    }

    getChildContext() {
        return {
            currentLanguage: this.props.currentLanguage
        };
    }
}

App.propTypes = {
    children: PropTypes.object.isRequired,
};

App.childContextTypes = {
    currentLanguage: PropTypes.string.isRequired
};

function select(state){
    return {user: state.auth.user, currentLanguage: state.lang.current};
}

function mapDispatchToProps(dispatch){
    return {
        changeLanguage: (lang) => dispatch(changeLanguage(lang))
    };
}

export default connect(select, mapDispatchToProps)(App);

And to finish, the translation files:

Translation Files

// en.js
export default {
    MyComponent: {
        someTranslatedText: 'Hello World'
    },
    SomeOtherComponent: {
        foo: 'bar'
    }
};

// fr.js
export default {
    MyComponent: {
        someTranslatedText: 'Salut le monde'
    },
    SomeOtherComponent: {
        foo: 'bar mais en français'
    }
};

What do you guys think?

I think is solves all the problem I was trying to avoid in my question: the translation logic doesn't bleed all over the source code, it is quite isolated and allows reusing the components without it.

For example, MyComponent doesn't need to be wrapped by translate() and could be separate, allowing it's reuse by anyone else wishing to provide the strings by their own mean.

[Edit: 31/03/2016]: I recently worked on a Retrospective Board (for Agile Retrospectives), built with React & Redux, and is multilingual. Since quite a lot of people asked for a real-life example in the comments, here it is:

You can find the code here: https://github.com/antoinejaussoin/retro-board/tree/master


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


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 => (
  <div className='someId'>
    {props.p.t('common.hello_world')}
  </div>
);
MyComponent.propTypes = {
  p: PropTypes.shape({t: PropTypes.func.isRequired}).isRequired,
}
export default translate(MyComponent);

Please tell me if you have any question/suggestion !


Yet another (light) proposal implemented in Typescript and based on ES6 & Redux & Hooks & JSON with no 3rd party dependencies.

Since the selected language is loaded in the redux state, changing the language becomes very fast without the need of rendering all pages, but just the affected texts.

Part 1: Redux setup:

/src/shared/Types.tsx

export type Language = 'EN' | 'CA';

/src/store/actions/actionTypes.tsx

export const SET_LANGUAGE = 'SET_LANGUAGE';

/src/store/actions/language.tsx:

import * as actionTypes from './actionTypes';
import { Language } from '../../shared/Types';

export const setLanguage = (language: Language) => ({
   type: actionTypes.SET_LANGUAGE,
   language: language,
});

/src/store/reducers/language.tsx:

import * as actionTypes from '../action/actionTypes';
import { Language } from '../../shared/Types';
import { RootState } from './reducer';
import dataEN from '../../locales/en/translation.json';
import dataCA from '../../locales/ca/translation.json';

type rootState = RootState['language'];

interface State extends rootState { }
interface Action extends rootState {
    type: string,
}

const initialState = {
    language: 'EN' as Language,
    data: dataEN,
};

const setLanguage = (state: State, action: Action) => {
    let data;
    switch (action.language) {
        case 'EN':
            data = dataEN;
            break;
        case 'CA':
            data = dataCA;
            break;
        default:
            break;
    }
    return {
        ...state,
        ...{ language: action.language,
             data: data,
            }
    };
};

const reducer = (state = initialState, action: Action) => {
    switch (action.type) {
        case actionTypes.SET_LANGUAGE: return setLanguage(state, action);
        default: return state;
    }
};

export default reducer;

/src/store/reducers/reducer.tsx

import { useSelector, TypedUseSelectorHook } from 'react-redux';
import { Language } from '../../shared/Types';

export interface RootState {
    language: {
        language: Language,
        data: any,
    }
};

export const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector;

/src/App.tsx

import React from 'react';
import { Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import languageReducer from './store/reducers/language';
import styles from './App.module.css';

// Set global state variables through Redux
const rootReducer = combineReducers({
    language: languageReducer,
});
const store = createStore(rootReducer);

const App = () => {

    return (
        <Provider store={store}>
            <div className={styles.App}>
                // Your components
            </div>
        </Provider>
    );
}

export default App;

Part 2: Dropdown menu with languages. In my case, I put this component within the navigation bar to be able to change the language from any screen:

/src/components/Navigation/Language.tsx

import React from 'react';
import { useDispatch } from 'react-redux';
import { setLanguage } from '../../store/action/language';
import { useTypedSelector } from '../../store/reducers/reducer';
import { Language as Lang } from '../../shared/Types';
import styles from './Language.module.css';

const Language = () => {
    const dispatch = useDispatch();
    const language = useTypedSelector(state => state.language.language);
    
    return (
        <div>
            <select
                className={styles.Select}
                value={language}
                onChange={e => dispatch(setLanguage(e.currentTarget.value as Lang))}>
                <option value="EN">EN</option>
                <option value="CA">CA</option>
            </select>
        </div>
    );
};

export default Language;

Part 3: JSON files. In this example, just a test value with a couple of languages:

/src/locales/en/translation.json

{
    "message": "Welcome"
}

/src/locales/ca/translation.json

{
    "message": "Benvinguts"
}

Part 4: Now, at any screen, you can show the text in the selected language from the redux setup:

import React from 'react';
import { useTypedSelector } from '../../store/reducers/reducer';

const Test = () => {
    const t = useTypedSelector(state => state.language.data);

    return (
        <div> {t.message} </div>
    )
}

export default Test;

Sorry for the post extension, but I tried to show the complete setup to clarify all doubts. Once this is done, it is very quick and flexible to add languages and use descriptions anywhere.