Reputation: 119
Please look at the following two files:
root-router.tsx
const rootStack = createNativeStackNavigator({
initialRouteName: mainRoute.route,
screenOptions: {
title: mainRoute.title,
headerRight: UserAppbarButton,
},
screens: {
[mainRoute.route]: mainRoute.page,
[userRoute.route]: {
screen: userRoute.page,
options: {
headerRight: undefined,
},
},
[modifyMealRoute.route]: modifyMealRoute.page,
[modifyIngredientRoute.route]: modifyIngredientRoute.page,
},
});
export const Navigation = createStaticNavigation(rootStack);
main.tsx
export const Main: FC = () => {
const prefTheme = useColorScheme();
const [isDark, setIsDark] = useState<boolean>(prefTheme === 'dark');
return (
<DarkmodeContext.Provider value={{ isDark, setIsDark }}>
<ThemeContext.Provider
value={isDark ? masterThemeDark : masterThemeLight}>
<Navigation theme={isDark ? navThemeDark : navThemeLight} />
</ThemeContext.Provider>
</DarkmodeContext.Provider>
);
};
I use the new static configuration method from React Navigation to setup my Navigation tree. I then wrap the resulting Navigation Element in a Context Provider.
Accessing the context value inside the screens is not possible. When trying to, only the default value provided to createContext
is returned.
I assume that is the case because the Navigation component is build before the Context Providers are added, which means no screen can access the context.
How can I use React Context while using the new static configuration from React Navigation? I like it more than dynamic, but I am pretty sure that dynamic would work.
Upvotes: 0
Views: 14
Reputation: 119
I found the actual reason it did not behave as expected: My ThemeContext component shares the same name as a component from the react navigation library, and I accidentally imported that one...
After making sure the correct things were imported, everything works as expected.
Upvotes: 0