Extremely simple react redux translation wrapper. Works well with redux saga.
yarn add knapcio/react-redux-translations
- Add reducer. the name must be 'translations'
const reducers = combineReducers({
//... other reducers
translations: translationReducer
})
- Prepare translation file. Example path: /public/translations/en.json
{
"hello_world": "Hey mate!"
}
- Load translations from file to state using i.e. redux saga
import { call, put } from 'redux-saga/effects';
import { actions as translationActions } from 'react-redux-translations';
function* translationSaga()
{
let lang = navigator.language.split('-')[0];
if(!["en", "pl"].includes(lang)) lang = "en";
const translationUrl = BASE_URL + '/public/translations/' + lang + '.json';
const translationFile = yield call(fetch, translationUrl);
const translation = yield call([translationFile, 'json']);
yield put(translationActions.setTranslations(translation));
}
export default translationSaga;
- Use the component
import { Translate } from 'react-redux-translations';
<Translate textId="hello_world"/>
- Helper function
If you need to use translation as a pure text you can firstly load translations to the service
import { translateHelper } from 'react-redux-translations';
function* translationSaga()
{
// ... previous saga code
const translation = yield call([translationFile, 'json']);
translateHelper.setTranslations(translation);
}
and then use it as a normal function anywhere in your app
import { translateHelper } from 'react-redux-translations';
translateHelper.translate('hello_world')