This plugin will setup your application for internationalization using:
- https://github.com/react-native-community/react-native-localize : To get data on the locales of the user that are defined in the OS settings
- https://github.com/formatjs/react-intl : To handle the actual management of translated strings
ignite add intl
ignite remove intl
At /
OSEDEA, we like simple, working solutions.
And when I say simple, I mean simple to USE. This setup is not super simple, but it provides a very simple, homogeneous way to add translations after: the translate
method.
To your top component (i.e. the one you plug into AppRegistry.registerComponent
), add the following changes (./i18n
being the file generated by the plugin if you add the translation files, or the templates/index.js
file of this repo):
import React, { Component } from 'react';
+ import * as RNLocalize from 'react-native-localize';
+ import { RawIntlProvider } from 'react-intl';
+ import { loadLocale, translate, registerLanguageListener, unregisterLanguageListener, intl, changeLanguage, currentLocale, getLocale } from './i18n';
class Root extends Component {
+ state = { locale: currentLocale };
+ componentDidMount() {
+ // Listen to changes made on the phone
+ RNLocalize.addEventListener('change', getLocale);
+ // setState if `changeLanguage` is called from anywhere in the app
+ registerLanguageListener(this.handleLocalizationChange);
+ // Loads the locale last saved in AsyncStorage
+ loadLocale().then((lang) => lang && changeLanguage(lang));
+ }
+ componentWillUnmount() {
+ // Cleanup
+ RNLocalize.removeEventListener('change', getLocale);
+ unregisterLanguageListener(this.handleLocalizationChange);
+ }
+ handleLocalizationChange = (locale: string) => {
+ this.setState({ locale });
+ };
render() {
return (
+ <RawIntlProvider value={intl}>
- <App />
+ <App />
+ </RawIntlProvider>
);
}
}
export default Root;
In any other component:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
+ import { translate } from '../i18n';
class SomeComponent extends Component {
render() {
return (
<View>
- <Text>Hey, how are you?</Text>
+ <Text>{translate({ id: 'hello' })}</Text>
</View>
);
}
}
export default SomeComponent;
If you are using react-navigation, follow this guide to setup your Tabs labels, etc.
This has been tested with React Native 0.61.4.
Please open an issue for any compatibility issues, or provide better interactivity/compatibility through opening a PR! 🙂