lets-i18n v0.2.5
How to use
npm install lets-i18nWrap your component tree with the
TranslationProviderand pass to itstranslationsprop the JSON file of translations.In the child component you want to translate, use the HOC
withTranslations, then atprop will be available so you can access your translation file.(Optional) A
languageprop is also available fromwithTranslationsas well. In order to use it, pass the desired language to theTranslationProvider.
Example
index.jsexport default class extends Component { render () { return ( <TranslationProvider translations={this.state.translations} language={'pt-br'}> <MyApp /> </TranslationProvider> ) }
componentDidMount () { const translations = require('./translations/pt-br.json')
this.setState({ translations })}
state = { translations: {} } }
> `MyApp.js`
```js
const MyApp = (props) => <p>{props.t('hello.world')} - language: {props.language}</p>
export default withTranslations(MyApp)
translations/pt-br.json{ "hello": { "world": "Olá, Mundo" } }
Development
For debugging purposes, when the NODE_ENV is not production, a translations prop is also available in the components wrapped by withTranslations with all the available keys and values:
const MyApp = (props) => {
console.log(props.translations)
return <p>{props.t('hello.world')} - language: {props.language}</p>
}
export default withTranslations(MyApp)Errors
- Translation file not found: in a non-production environemnt it will not raise any error. In
productionit will print an error to the console:
console.error('TRANSLATION_ERROR: Please, provide the files to translate.')- Translation key not found: it will raise different errors in
productionand other environments:
Production
The last property of the translation string will be rendered:
<div>{t('this.translation.string.does.not.exist')}</div>Will be rendered as:
<div>exist</div>Other environments
<div>{t('this.translation.string.does.not.exist')}</div>Will be rendered as:
<div>TRANSLATION_ERROR: "this.translation.string.does.not.exist" does not exist.</div>