Skip to content

Simple react redux translation solution - perfect for using with redux saga

License

Notifications You must be signed in to change notification settings

knapcio/react-redux-translations

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-redux-translations

Extremely simple react redux translation wrapper. Works well with redux saga.

Installation

yarn add knapcio/react-redux-translations

Usage

  1. Add reducer. the name must be 'translations'
const reducers = combineReducers({
  //... other reducers
  translations: translationReducer
})
  1. Prepare translation file. Example path: /public/translations/en.json
{
  "hello_world": "Hey mate!"
}
  1. 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;
  1. Use the component
import { Translate } from 'react-redux-translations';

<Translate textId="hello_world"/>
  1. 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')

About

Simple react redux translation solution - perfect for using with redux saga

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published