I am using native base + react-navigation in an app and need to change the theme of the app. As soon as I change the theme the react-navigation update that easily but the problem is that the native base component theme does not change. It looks odd to the user.
I had used this code to change the theme of the app
<StyleProvider style={getTheme(theme === 'LIGHT' ? platform : material)}>
<Container>
<NavigationContainer
theme={theme === 'LIGHT' ? DefaultTheme : MyThemeDark}>
<Stack.Navigator
initialRouteName={isProfile ? 'Root' : 'Selection'}>
..................
</Stack.Navigator>
</NavigationContainer>
</Container>
</StyleProvider>
As I said React navigation theme is updating correctly but the native base theme is not updating.
For native base 3, to change the theme, you can use the React Native hook useColorScheme
to get the current theme of the device and update the theme using native base method setColorMode
.
I believe the code needs to be added as child component of NativeBaseProvider
. For example, may not work in App.js if you define NativeBaseProvider
there.
import React from "react";
import { useColorMode } from 'native-base';
import { useEffect } from 'react';
import { Alert, useColorScheme } from 'react-native';
export const UseColorMode = () => {
const colorScheme = useColorScheme();
const {
setColorMode,
} = useColorMode();
useEffect(() => {
if (colorScheme) {
Alert.alert(`${colorScheme}`)
setColorMode(colorScheme);
}
}, [colorScheme, setColorMode])
return (<></>)
}
App.js
const App = () => {
return (<NativeBaseProvider>
<UseColorMode/>
</NativeBaseProvider>)
}