Home > OS >  Update variable in all screens of the App React Natice
Update variable in all screens of the App React Natice

Time:03-23

My app is both in French and English. I want the user to be able to change the language on any page and when they navigate to any other screen I want the change to be reflected.

For instance, I have A.js

const A = (props) => {
  const [language, setLanguage] = useState('')
  return (
   <View style ={styles.container}>
            <Button onPress ={()=>setLanguage('french')}>{language==="french" ? changer la langue : change the language}
            </Button>
        </View>  
  )
}
Now when I go to any screen after pressing the button I want the content to be rendered in French and if I change the language in another screen I want changer la langue to be rendered in this screen

Memory leakage

const [language, setLanguage] = useState('') 
    const [visible, setVisible] = useState(false)
    const {t} = useTranslation();    
    const fetchLanguage =  async () =>{
        try{
            const currentLanguage = await AsyncStorage.getItem('language')
            if (currentLanguage === null ){
                setVisible(true)
            }
            else{
                setLanguage (currentLanguage)
                i18n.changeLanguage(currentLanguage)
            }
        }catch (e){
            console.log(e)
        }
       
    }
    useEffect (()=>{
        fetchLanguage()
    }, [])

CodePudding user response:

You can go ahead make a context to manage that manually however that will be something like recreating wheel.

You can right away use i18next and react-i18next to support app wide localisation with just minimal setup like below in React Native too.

import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';

// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them separated from your code: 
https://react.i18next.com/guides/multiple-translation-files)
const resources = {
  en: {
    "title": "Hello",
  },
  fr: {
    "title": "Bonjour",
  },
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    compatibilityJSON: 'v3',
    lng: 'en',  //default language.
    interpolation: {
      escapeValue: false, // react already safes from xss
    },
});

export default i18n;

Then you can easily use these translations in app via easy ways as described in the docs

Such as

const {t} = useTranslations();
....
return (
  <Text>{t('title')}</Text>
)

Update: Let user change the language from within the app

You can still use this i18next to let your users change the language from within the app by just calling a simple method on i18 instance as documented here.

i18n.changeLanguage('fr');
  • Related