mdemet
mdemet

Reputation: 53

Localization of React Native navigators

I am building an app where the users are prompted to choose their language the first time they launch the app. The language is then stored locally using AsyncStorage.

Every time the app launches the language is retrieved from storage and saved into the global.lang variable to be used by all components:

AsyncStorage.getItem('settings', (err, item) => {
  global.lang = item.lang; 
});

When I use the global.lang variable in the render() method in any component everything seems to be ok. However I run into trouble when trying to use the same variable when initializing my navigators:

const TabNavigator = createBottomTabNavigator(
 {
    Home: {
      screen: HomeScreenNavigator,
      navigationOptions:{
        title: strings['en'].linkHome,  --> this works
      }
    },
    News: {
      screen: NewsScreen,
      navigationOptions:{
        title: strings[global.lang].linkNews,  --> this fails
      }
    }
});

I believe that this because the value is not retrieved from AsyncStorage by the time that the navigators are constructed. If I set the global.lang manually (eg. global.lang = 'en';) it seems to be OK, but not when I try to retrieve it from the storage.

Is there something that I am missing? Could I initialize the navigator with a default language and change the title later based on the value retrived?

Any help would be greatly appreciated.

Upvotes: 0

Views: 699

Answers (1)

RegularGuy
RegularGuy

Reputation: 3686

The navigators are constructed in the app launch. So you would need to use some placeholder text and use the method described here where you change all screen titles based on the screen key...

Or... this sounds insane and i have never tried it. But you can use a loading screen where you retrieve the languaje settings. then... via conditional rendering you "render" a navigator component . Idk if it would work the same way , but you can try it. below some code that i just created for this purpose

export default class MainComponent extends React.Component {
constructor(props) {
    super(props);
    this.state = { hasLanguage:false};}


    componentDidMount(){
        this.retrieveLanguage()
    }

    async retrieveLanguage(){
        //await AsyncStorage bla bla bla

        //then

        this.setState({hasLanguage:true})
    }

render() {
    return (
             {
                this.state.hasLanguage?
                <View>
                        //this is a view that is rendered as a loading screen
                </View>:
                <Navigator/>//this will be rendered, and hence, created, when there is a language retrieved

             }
      );
   }
}   

Again. I don't know if react navigation creates the navigator at render . If so. When it creates a navigator , there should be the languaje to be used there

Upvotes: 1

Related Questions