A Redux implementation for simple React and React Native language i18n.
npm install --save redux-lang
Or include the following in your web page:
<!-- minified version -->
<script src="https://unpkg.com/redux-lang/dist/index.min.js"></script>
<!-- non-minified version -->
<script src="https://unpkg.com/redux-lang/dist/index.js"></script>
Create a map of language strings, e.g. assets/lang/en.js:
export default {
home: {
welcome: 'Hello, %s!'
}
}
Create an index file for each of your languages, e.g. assets/lang/index.js:
import en from './en'
import fr from './fr'
export default {
en,
fr
}
Initialise ReduxLang in your application, e.g. src/middleware/lang.js, using your dictionary file
import { createLang } from 'redux-lang'
import dictionary from '../../assets/lang/index'
const reduxLang = createLang(dictionary)
export default reduxLang
Add the redux-lang reducer to your root reducer. This is a function which takes the initial language key as an argument.
import { combineReducers } from 'redux'
import { langReducer } from 'redux-lang'
export default combineReducers({
// All your other reducers here
locale: langReducer('en')
})
Decorate your component with reduxLang(). This will provide your component with props which you can use to access your language strings and set the current language. You need to pass a second argument to represent the 'screen key' in your dictionary.
import React from 'react'
import reduxLang from '../middleware/lang'
const Demo = ({t, locale, setLocale}) => {
console.log(locale) // 'en'
return (
<p>{t('welcome', ['James'])}</p>
)
}
export default reduxLang('home')(Demo)
import React, { Component } from 'react'
import { View, Text } from 'react-native'
import reduxLang from '../middleware/lang'
const Demo = ({t, locale, setLocale}) => {
console.log(locale) // 'en'
return (
<View style={{top: 20}}>
<Text>{t('welcome', ['James'])}</Text>
</View>
)
}
export default reduxLang('home')(Demo)
See examples for more detailed implementations.