Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set RTL / LTR in React-Native

I want to set my app'a direction dynamically, by a property. React Native allows to set direction according to device's default language, but I want to select direction by locale property I have on my user's data.

Up until now, I used this code in my MainApplication.java to force only LTR for all users:

I18nUtil sharedI18nUtilInstance = I18nUtil.getInstance();
sharedI18nUtilInstance.allowRTL(getApplicationContext(), false);

I'm looking now for a way to kind of switch the 'false' in code, to a boolean that changes according to my user's locale. Have no idea how to achieve that...

Extra's info:

  • Android device
  • RN version: 0.40.0
like image 378
efratyo Avatar asked Oct 29 '22 13:10

efratyo


1 Answers

you can use I18nManager to force language direction

constructor() {
    super();
    //set user language b default english
    this.state = {
        lang: 'en'
    }
}


componentWillMount() {
          //get user lang form AsyncStorage 
    AsyncStorage.getItem('lang').then((value) => {
         //now you should forceRTL by Language and set Language in your states
        if ((value === 'ar' || value === 'fa' )) {
            I18nManager.forceRTL(true);
        } else {
            I18nManager.forceRTL(false);
        }
        return this.setState({
            lang: value 
        });
    }).done();
}
like image 145
Mortada Jafar Avatar answered Nov 02 '22 22:11

Mortada Jafar