score:111
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
score:0
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}>
<h2>{language.title}</h2>
<p>{language.description}</p>
<p>{language.amount}</p>
<button>{languageform.save}</button>
</div>
);
}
}
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);
score:1
if not yet done having a look at https://react.i18next.com/ might be a good advice. it is based on i18next: learn once - translate everywhere.
your code will look something like:
<div>{t('simplecontent')}</div>
<trans i18nkey="usermessagesunread" count={count}>
hello <strong title={t('nametitle')}>{{name}}</strong>, you have {{count}} unread message. <link to="/msgs">go to messages</link>.
</trans>
comes with samples for:
- webpack
- cra
- expo.js
- next.js
- storybook integration
- razzle
- dat
- ...
https://github.com/i18next/react-i18next/tree/master/example
beside that you should also consider workflow during development and later for your translators -> https://www.youtube.com/watch?v=9nozjhgmyqe
score:2
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.
gettext
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:
- i18next, with usage described by this arkency.com blog post
- jed, with usage described by the sentry.io 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. sentry.io 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.
icu
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 sentry.io 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!');
i18next.t(
'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!')();
mf.compile(
'the first 4 letters of the english alphabet are: {s1}, {s2}, {s3} and {s4}'
)({ s1: 'a', s2: 'b', s3: 'c', s4: 'd' });
score:3
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.
score:6
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 ap
object that exposes 4 methods :t(key)
: original polyglot t functiontc(key)
: capitalized translationtu(key)
: upper-cased translationtm(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 thep
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 !
score:19
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
Source: stackoverflow.com
Related Query
- React / Redux and Multilingual (Internationalization) Apps - Architecture
- Integrating React and OpenLayers within a Redux Architecture
- Architecture example for a multi-language application using React, React Redux or React Context, and Material UI
- React and Redux architecture issues
- React and Redux Architecture
- Difference between component and container in react redux
- Cannot read property '.then' of undefined when testing async action creators with redux and react
- Using compose() and connect() together in React JS redux
- Dealing with local state in react and redux
- Building hybrid React apps for iOS and Android with native performance
- Fractal Project Structure with React and Redux - pros/cons
- Calling an action from a different reducer with React and redux
- Can I send an AJAX call in React and Redux without action creators and reducers?
- Design Redux actions and reducers for a React reusable component
- VSCode keeps asking to import React on NextJS and React 17 apps
- react redux architecting table actions and reducers
- Performance issues with a tree structure and shouldComponentUpdate in React / Redux
- React Native: HeadslessJS and Redux - How to access store from task
- react context vs redux vs hooks, which one should consider and how each one is different
- React Navigation: How to update navigation title for parent, when value comes from redux and gets updated in child?
- No need for state in React components if using Redux and React-Redux?
- Correct way to throttle HTTP calls based on state in redux and react
- Decoupling React Components and Redux Connect
- Paginate date-specific results from an API with React and Redux
- React and Redux: Managing Redux Custom Middleware List
- React Redux and react-router-dom
- Auto save form fields in react and redux
- React components lifecycle, state and redux
- How to setup Ember like computed properties in Immutablejs and Redux and Flux and React
- Best practice to handle errors in Redux and React
More Query from same tag
- Can't update the font size in react using tailwindcss library
- NavLink exact prop not working for react-router-dom 6
- Authentication and Authorization in React app
- error network while installing create-react-app
- Sibling Functional Components communication in reactjs
- Apollo and GraphQL CORS
- How to declare a React component extending package component in Typescript?
- How to modify a certain object in array of objects that stored in redux state
- how can I unit test an output of HTML code
- Remove an object from an array of if not Present in Array
- react - maximum update depth exceeded using react-table
- Why are JS / React much quicker than WebAssembly / Rust?
- Change image on click - React
- Ionic react: How to properly type (typescript) event object parameter in delegated anonymous onIonChange event handler
- call api response on getting in react js
- Babel 7 + react + redux => crash on IE / old FF
- onClick handler is applying on all elements after map
- How to show an error message when no data is found while filtering
- Visual Studio npm modules
- Error when styling React components imported from index file, but not when importing directly from component file
- How to use React client to receive a message from a Socket.io server?
- Webpack, React & Mocha test: Missing class properties transform
- How to pass Material UI data to Formik?
- ReactJS/JSX support in Netbeans IDE
- Extracting styles from material ui component
- delete song from redux state within reducer
- Missing semicolon linting error with typescript
- How to test multiple paths using the _.get method of lodash?
- Combining react and jade
- How to use Typescript with React Router and match