Accepted answer

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 (
                { this.props.strings.sometranslatedtext }

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 = {

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 (
                <menu onlanguagechange={this.props.changelanguage}/>
                <div classname="">



    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:


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 (
            <div classname={this.props.classes.somestyle}>
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:


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


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


import lang from '../lib/lang.js';


if not yet done having a look at might be a good advice. it is based on i18next: learn once - translate everywhere.

your code will look something like:

<trans i18nkey="usermessagesunread" count={count}>
  hello <strong title={t('nametitle')}>{{name}}</strong>, you have {{count}} unread message. <link to="/msgs">go to messages</link>.

comes with samples for:

  • webpack
  • cra
  • expo.js
  • next.js
  • storybook integration
  • razzle
  • dat
  • ...

beside that you should also consider workflow during development and later for your translators ->


from my research into this there appears to be two main approaches being used to i18n in javascript, icu and gettext.

i've only ever used gettext, so i'm biased.

what amazes me is how poor the support is. i come from the php world, either cakephp or wordpress. in both of those situations, it's a basic standard that all strings are simply surrounded by __(''), then further down the line you get translations using po files very easily.


you get the familiarity of sprintf for formatting strings and po files will be translated easily by thousands of different agencies.

there's two popular options:

  1. i18next, with usage described by this blog post
  2. jed, with usage described by the post and this react+redux post,

both have gettext style support, sprintf style formatting of strings and import / export to po files.

i18next has a react extension developed by themselves. jed doesn't. appear to use a custom integration of jed with react. the react+redux post, suggests using

tools: jed + po2json + jsxgettext

however jed seems like a more gettext focussed implementation - that is it's expressed intention, where as i18next just has it as an option.


this has more support for the edge cases around translations, e.g. for dealing with gender. i think you will see the benefits from this if you have more complex languages to translate into.

a popular option for this is messageformat.js. discussed briefly in this blog tutorial. messageformat.js is actually developed by the same person that wrote jed. he makes quite stong claims for using icu:

jed is feature complete in my opinion. i am happy to fix bugs, but generally am not interested in adding more to the library.

i also maintain messageformat.js. if you don't specifically need a gettext implementation, i might suggest using messageformat instead, as it has better support for plurals/gender and has built-in locale data.

rough comparison

gettext with sprintf:

i18next.t('hello world!');
    'the first 4 letters of the english alphabet are: %s, %s, %s and %s', 
    { postprocess: 'sprintf', sprintf: ['a', 'b', 'c', 'd'] }

messageformat.js (my best guess from reading the guide):

mf.compile('hello world!')();
    'the first 4 letters of the english alphabet are: {s1}, {s2}, {s3} and {s4}'
)({ s1: 'a', s2: 'b', s3: 'c', s4: 'd' });


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:


export type language = 'en' | 'ca';


export const set_language = 'set_language';


import * as actiontypes from './actiontypes';
import { language } from '../../shared/types';

export const setlanguage = (language: language) => ({
   type: actiontypes.set_language,
   language: language,


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;
        case 'ca':
            data = dataca;
    return {
        ...{ 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;


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;


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={}>
                // your components

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:


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 (
                onchange={e => dispatch(setlanguage(e.currenttarget.value as lang))}>
                <option value="en">en</option>
                <option value="ca">ca</option>

export default language;

part 3: json files. in this example, just a test value with a couple of languages:


    "message": "welcome"


    "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 =>;

    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.


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'>
mycomponent.proptypes = {
  p: proptypes.shape({t: proptypes.func.isrequired}).isrequired,
export default translate(mycomponent);

please tell me if you have any question/suggestion !


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:

    {"code":"en","name": "english"},
     "thank you":"شكراً",
     "you have {count} new messages":"لديك {count} رسائل جديدة"

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

Related Query

More Query from same tag