Easy internationalization for Next.js and React apps
-
npm install lets-i18n
-
Wrap your component tree with the
TranslationProvider
and pass to itstranslations
prop the JSON file of translations. -
In the child component, you want to translate, use the HOC
withTranslations
, then at
prop will be available so you can access your translation file. -
(Optional) A
language
prop is also available fromwithTranslations
as well. In order to use it, pass the desired language to theTranslationProvider
.
index.js
export 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
const MyApp = (props) => <p>{props.t('hello.world')} - language: {props.language}</p>
export default withTranslations(MyApp)
translations/pt-br.json
{
"hello": {
"world": "Olá, Mundo"
}
}
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)
- Translation file not found: in a non-production environment it will not raise any errors. In
production
it 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
production
and other environments:
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>
<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>