I'm trying to implement the Context API to react navigation 5 in order to pass the locale globally across the entire App.
I'm following the example shown in Expo documentation about localization: https://reactnavigation.org/docs/localization/
App.js
import React from 'react';
import { NavigationContainer } from "@react-navigation/native";
import * as Localization from 'expo-localization';
import i18n from 'i18n-js';
import AppNavigator from './AppNavigator';
import StartupScreen from "../screens/StartupScreen";
const en = {
hello: 'Hello',
welcome: 'Welcome',
};
const es = {
hello: 'Hola',
welcome: 'Bienvenido',
};
i18n.fallbacks = true;
i18n.translations = { en, es };
export const LocalizationContext = React.createContext();
export default function App() {
const [locale, setLocale] = React.useState(Localization.locale);
const localizationContext = React.useMemo(
() => ({
t: (scope, options) => i18n.t(scope, { locale, ...options }),
locale,
setLocale,
}), [locale]);
console.log(locale);
return (
<LocalizationContext.Provider value={localizationContext}>
<NavigationContainer>
<AppNavigator />
</NavigationContainer>
</LocalizationContext.Provider>
);
}
Everything seems fine and the App is loaded as expected. When I then try to go to the Language screen which contains the following code
import React, { useState, useContext } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import i18n from 'i18n-js';
const en = {
hello: 'Hello',
welcome: 'Welcome',
};
const es = {
hello: 'Hola',
welcome: 'Bienvenido',
};
i18n.fallbacks = true;
i18n.translations = { en, es };
const LanguageScreen = (props) => {
const { t, locale, setLocale } = useContext(LocalizationContext);
return (
<View style={styles.screen}>
<Text>Language Screen</Text>
<StatusBar hidden />
<Text style={styles.text}>
Current locale: {locale}.{' '}
{locale !== 'en' && locale !== 'es'
? 'Translations will fall back to "en" because none available'
: null}
</Text>
<Text>{t('hello')}</Text>
<Text>{t('welcome')}</Text>
{locale === 'en' ? (
<View>
<Button title="Switch to Spanish" onPress={() => setLocale('es')} />
</View>
) : (
<View>
<Button title="Switch to English" onPress={() => setLocale('en')} />
</View>
)}
</View>
);
};
export default LanguageScreen;
I get an error "Can't find variable: LocalizationContext"
Looks like the LocalizationContext wrapper around the is not propagating.