Advertisement
duongntb94

[Feature] [RN] Set up react-i18next for localisation

Mar 25th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Step 1: Install i18next and react-i18next. For react <= 0.58.6
  2. yarn add i18next react-i18next@legacy
  3.  
  4. // Step 2: Install code below as localisation center.
  5. import i18next from 'i18next';
  6. import { reactI18nextModule } from 'react-i18next';
  7. import enAU from './lang/enAU';
  8. import viVN from './lang/viVN';
  9.  
  10. i18next.use(reactI18nextModule).init({
  11.   lng: 'enAU',
  12.   debug: true,
  13.   resources: {
  14.     enAU: {
  15.       translation: enAU,
  16.     },
  17.     viVN: {
  18.       translation: viVN,
  19.     },
  20.   },
  21. });
  22.  
  23. export default i18next;
  24.  
  25. // Step 3: Import locationsation file in the header of index.js file and set up with withNamespace as a HOC componenents.
  26. import 'src/locale';
  27. import { withNamespaces } from 'react-i18next';
  28.  
  29. class App extends React.Component {
  30.   static router = AppContainer.router;
  31.  
  32.   render() {
  33.     const { t } = this.props;
  34.     return (
  35.       <View style={styles.container}>
  36.         <AppContainer
  37.           screenProps={{ t }}
  38.           {...this.props}
  39.           ref={(ref) => {
  40.             NavigationService.setTopLevelNavigator(ref);
  41.           }}
  42.         />
  43.       </View>
  44.     );
  45.   }
  46. }
  47.  
  48. // Add with name spaces HOC and observe to the app.
  49. export default withNamespaces('common', {
  50.   bindI18n: 'languageChanged',
  51.   bindStore: false,
  52.   wait: false,
  53. })(observer(App));
  54.  
  55. // The first node in json will be the namespace, you can specific withNamespaces('nameOfNameSpace') for your component. No specific will use all namespace.
  56.   common: {
  57.     action: {
  58.       ok: 'OK',
  59.       cancel: 'Cancel',
  60.     },
  61.     email: 'Email',
  62.     password: 'Password',
  63.   }
  64. // So if you want to get ok, it will be common.action.ok
  65.  
  66. // Set localisation for the navigation options.
  67. static navigationOptions = ({ navigation, screenProps }) => {
  68.     const onPressLeft = navigation.getParam('onPressLeft');
  69.     const { t } = screenProps;
  70.     return {
  71.       title: t('changeLanguage.title'),
  72.       headerLeft: (
  73.         <TouchableIcon
  74.           onPress={onPressLeft}
  75.           name='hambuger'
  76.           iconStyle={styles.iconLeft}
  77.           style={styles.buttonLeft}
  78.         />
  79.       ),
  80.     };
  81.   }
  82.  
  83. // Change language with i18n. Remember you need to wrap withNamespaces as HOC
  84. const { i18n } = this.props;
  85. i18n.changeLanguage('en_US')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement