react-switch-lang
React Multi-language Higher Order Component with cookie support.
Installation
npm install react-switch-lang --save
Usage
en.json
th.json
SomeComponent.js
;; // Translation Higher Order Component;;; // Do this two lines only when setting up the application;; // If you want to remember selected language; Component { ; }; { const t = thisprops; return <div> <button type="button" onClick=this> Switch language </button> </div> } SomeComponentpropTypes = t: PropTypesfuncisRequired; SomeComponent;
Injected Method
If using the Higher Order Component translate(SomeComponent)
t(path, params, lang)
Get text function, will return the translated string
Params | Type | Description |
---|---|---|
path | string | translation path that identifies the text |
params | object | (optional) {'param': 'value', ...} each param will be set on the string in its correct location |
lang | string | (optional) force select language with translation key, in this example 'en' or 'th' |
Exported Methods
setDefaultTranslations(translations)
Sets the translations
Params | Type | Description |
---|---|---|
translations | object | { "en": { "hello": "Hello" } } |
setTranslations(translations)
Same as setDefaultTranslations, but this will update all components using translations
Params | Type | Description |
---|---|---|
translations | object | { "en": { "hello": "Hello" } } |
setDefaultLanguage(key)
Set the default application language, when current language does not have translation text method t() will fallback with this default language Note: this method will set current language but not update components
Params | Type | Description |
---|---|---|
key | string | translation key, in this example 'en' or 'th' |
setLanguage(key)
Set current language, this will update all components using translations
Params | Type | Description |
---|---|---|
key | string | translation key, in this example 'en' or 'th' |
setLanguageCookie(name, option, reqCookie)
Set the language cookie name, will setLanguage form this cookie and store language key back to cookie when call setLanguage
Params | Type | Default | Description |
---|---|---|---|
name | string | 'language' |
(optional) name of cookie to store in browser |
option | object | { path: '/', maxAge: 157680000 } |
(optional) cookie option base on "universal-cookie", default age is 5 years |
reqCookie | string | undefined |
(optional) the express cookie header (req.headers.cookie), this is required if you use server-side rendering such as Next.js |
getLanguages()
Return all translations key. Example: ['en', 'th']
getDefaultLanguage()
Return the default fallback language
getLanguage()
Return the current selected language
t(key, params, lang)
Same as t() method above