react-native-i18n
react-native-i18n copied to clipboard
Using links/navigation to screens in translations
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 Not really. This library doesn't handle navigation.
That's right. This seems like out of the scope of the library. However, you can do the following:
- Create your navigation screens with react navigation:
{
LoginScreen: { screen: LoginScreen },
WelcomeScreen: { screen: WelcomeScreen, navigationOptions: { header: null } },
}
- 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ış"
}
}
- 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} />;
}
};
}
- 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.