Redux Multilanguage
A higher-order component used with Redux to support multilanguage
Installation
npm install --save redux-multilanguage
or
yarn add redux-multilanguage
Setup
- Prepare language.json files. File name should be a unique language code. For example:
//vi.json "Title": "Tieu de" "Name": "Ten" "Language": "Ngon ngu" //en.json "Title": "Title" "Name": "Name" "Language": "Language"
- Create
multilanguage
reducer in your root reducer:
// reducers.js multilanguage: //...
- Connect your component to
redux-multilanguage
:
// App.jsimport React from 'react'import languageLoader multilanguage changeLanguage loadLanguages from 'redux-multilanguage'import connect from 'react-redux' Component state = language: 'en' { this } { // Below is to load languages, must call this once on app start, // and when user switch to new language that haven't loaded yet. thisprops } { const languageCode = etargetvalue // To change language: thisprops } { const /* Below props are passed by 'multilanguage' HOC. 'strings' is the JSON of the language file. For example, if 'currentLanguageCode' is 'en', then 'strings' is the content of 'en.json' */ strings currentLanguageCode } = thisprops return <div> strings"Title" Change language: <select = = > <option ="en">en</option> <option ="vi">vi</option> </select> </div> }
For more, see full working example.
APIs
Below are what exported by redux-multilanguage
-
[HOC]
multilanguage(WrappedComponent)
: Use this to wrap your component, wrapped component will have these passed props:strings
: The JSON of current selected language.currentLanguageCode
: The code of current language, to change this, dispatchchangeLanguage()
-
[action creator]
loadLanguages(config)
: Load languages, this action should be dispatched when app start or dispatched mutiple times when ever demand to lazy-load languages.-
config.languages
: An object, keys are language codes, equivalent values are json of code-string values. Example:dispatch(loadLanguages({ languages: { vi: {Title: 'Tieu de', Name: 'Tên'}, en: {Title: 'Title', Name: 'Name'} } }))
-
-
[action creator]
changeLanguage(languageCode)
: an action creator to change language. Example usage:dispatch(changeLanguage('en'))
-
createMultilanguageReducer(initState)
: returns a reducer for multilanguage in redux storeinitState.currentLanguageCode
: language code to be loaded by default