Permalink
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
75 lines (52 sloc) 2.62 KB

Integration with react-navigation

Our framework setup is completed, so is the toggle language feature. Everything seems to be working, except for one thing. The header text is not getting re-rendered on language change. Have a look at the screenshot below.


The current language is `Hindi`. Everything changes in the UI except the header.

But why is this happening?

We are using translate function in the routes file. Right?

Answer: Yes we are, but how will the router know that it has to re-render?

Luckily, react-navigation provides us with a feature to pass screenProps. ScreenProps will be passed to each navigator instance's navigationConfig. We can pass screenProps as a prop to the Router component in our App.container.

App.container.js


However, change in screenProps will not cause re-rendering of Router. Have a look at the issue here to know why.

To fix this, we would use a function instead of an object for our navigationConfig (have a look at Header Configuration topic here). ScreenProps are passed to this function and we can use them to get the currentLanguage and then translation.

Instead of

navigationOptions: {
  title: translate('HOME_startTakingNotes')
}

we will do

navigationOptions: ({screenProps}) => {
  const title = I18n.translate('HOME_startTakingNotes', screenProps.language);
  return {title};
};

Doing this will cause the header text to change dynamically based on the currentLanguage. Let's create a utility for this so that we don't have to rewrite this function.

language.utils.js

export const translateHeaderText = (langKey) => ({screenProps}) => {
  const title = I18n.translate(langKey, screenProps.language);
  return {title};
};

Now let's use this utility in all our routes file. Example usage:

routes/index.js

navigationOptions: translateHeaderText('HOME_startTakingNotes')

Our app now supports internationalization without any bugs. 🕵🏻

The code till here can be found on the branch chapter/13/13.3