react-native-i18n icon indicating copy to clipboard operation
react-native-i18n copied to clipboard

Using links/navigation to screens in translations

Open udarts opened this issue 6 years ago • 2 comments

Hi There,

I like this I18n very much. I have a feature request. It would be nice to be able to use links/navigation to screens in translations. For example, specify the translation 'tag', add the link/navigation to a screen and on which word('s)/sentence(s) the link/navigation to a screen should be working on.

I hope this makes sense.

udarts avatar Jun 21 '18 06:06 udarts

@udarts Not really. This library doesn't handle navigation.

zoontek avatar Jul 12 '18 15:07 zoontek

That's right. This seems like out of the scope of the library. However, you can do the following:

  1. Create your navigation screens with react navigation:
{
  LoginScreen: { screen: LoginScreen },
  WelcomeScreen: { screen: WelcomeScreen, navigationOptions: { header: null } },
}
  1. Add a locale config. Note: I use a general key for common keywords:
{
  "WelcomeScreen": {
    "personal": "Bireysel"
  },
  "LoginScreen": {
    "user": "Kullanıcı",
    "password": "Şifre"
  },
  "general": {
    "enter": "Giriş",
    "logout": "Çıkış"
  }
}
  1. Create a Higher Order Component
import I18n from 'react-native-i18n';
import React from 'react';

export default function addI18n(WrappedComponent) {
  return class extends React.PureComponent {

    static navigationOptions = WrappedComponent.navigationOptions;

    i18n = (name, params = {}) => {
      if (name.indexOf('general') !== 0) {
        const { routeName } = this.props.navigation.state;
        return I18n.t(`${routeName}.${name}`, params);
      }
      return I18n.t(name, params);
    };

    render() {
      return <WrappedComponent {...this.props} i18n={this.i18n} />;
    }
  };
}
  1. Use HOC in your component from props. Note: I'm using babel-plugin-transform-decorators-legacy to simply HOC
//...
import addI18n from '../hocs/addI18n';

@addI18n
class LoginScreen extends Component {
  static navigationOptions = {
    title: ' ',
  }

  render() {
    const { i18n } = this.props;
    return (<View>
      <TextInput placeholder={i18n('user')} />
      <TextInput placeholder={i18n('password')} secureTextEntry />);
      <Button title={i18n('general.enter')} />
  }

}

So here, i18n('user') will use i18n.t('LoginScreen.user') and i18n('general.enter') will use the same.

cihadturhan avatar Jul 17 '18 10:07 cihadturhan