react-translator2
A deadly simple i18n translate plugin for React, ready for Server Side Rendering.
Demo
https://JounQin.github.io/react-translator
Related
Usage
yarn add react-translator2
// `lodash.merge` for example, you must pass itTranslator.merge = merge // If you want to define translations in component only, no need to set it on initializeTranslator.addTranslationstranslations:
translations
is often generated via require.context
provided by webpack
from *.{locale}.i18n.json
:
Then you need to use withTranslator
to wrap your component to enable translator prop t
and prop locale
+ defaultLocale
, the reference value of t
will never change what means there will be only one translator instance. And prop locale
is string will be changed when you set value of t.locale
.
If you are trying to get a non-exist key or value is undefined, you will get a warning in console on development. And if you want to ignore it, pass a third parameter ignoreNonExist: boolean
: $t('non-exist-key', null, true)
.
If you want to watch locale change in any component(withTranslator
is watching inside with enables rendering on locale
and defaultLocale
change), you can use translator.watch
API like following:
const unwatch = thispropstranslator // if you want to unwatch changes, maybe in `componentWillUnmount` lifecycle
Or you can also listen componentDidUpdate
lifecycle:
{ ifprevPropslocale !== thispropslocale // locale changed }
If you want to change locale on client:
{ thispropstranslator
SSR related
You'd better to detect user custom locale via cookie and fallback to accept-language on first request.
And you need to generate a single translator instance for every user request (cache by locale would be better), koa
for example:
app.use
template syntax
Translation key should be string, but .
(dot) will be parsed as nested key, it will also work in template!
// will try to find `a.b.c` on your custom transition, if a is falsy, will render undefined and try default locale // render `nested value` // render `nested template`
Array is also supported, .index
(dot) or [index]
can both be used!
// nested with array key and template// render `1`
Feature Request or Troubleshooting
Feel free to create an issue.