Home > database >  What is the best way to change the Status Bar color for all screens using nested navigation in React
What is the best way to change the Status Bar color for all screens using nested navigation in React

Time:11-22

I am currently using Expo and React Navigation to toggle between Dark Theme and Light Theme for my app. The only issue is that I’m not able to change the status bar color on iOS based on the theme.

I have a Tab Navigator nested inside of Drawer Navigator, but I’m having trouble figuring out how to change the status bar color on iOS when I toggle the theme for all screens in the nested navigation. This is what part of my drawer navigator looks like.

 <themeContext.Provider value={themeData}>
    <NavigationContainer theme={theme == 'Light' ? CustomDefaultTheme : CustomDarkTheme}>
      <Drawer.Navigator
        screenOptions={{
          headerShown: false,
          swipeEdgeWidth: 0,
          drawerActiveBackgroundColor: '#e8e4f0',
          drawerActiveTintColor: '#8a76b6',
          drawerInactiveBackgroundColor: 'transparent',
          drawerInactiveTintColor: '#bcbcc1',

        }}

CodePudding user response:

You need to use StatusBar from react-native. I personally put it next to the Navigator (whatever you named it) in the App.tsx/App.jsx. Like example below:

<>
  <StatusBar
  backgroundColor={
    theme == "Light"
      ? CustomDefaultTheme
      : CustomDarkTheme
  }
  barStyle={
    theme == "Light"
      ? CustomDefaultTheme
      : CustomDarkTheme
  }
  />
  <Navigation />
</>

You can adjust the barStyle and backgroundColor as you see fit.

For more details about StatusBar props, check here

CodePudding user response:

You can use react-native's StatusBar methods to change it background or barStyle -

StatusBar.setBarStyle(theme == 'Light' ? 'dark-content' : 'light-content');
StatusBar.setBackgroundColor(theme == 'Light' ? '#fff' : '#000')

call this above functions when you change theme.

another way you can change it from root component if you want to change Status bar background for all screen then you can do like this -

import { SafeAreaView, StatusBar } from 'react-native'

...
<SafeAreaView style={{flex: 1}}>
  <StatusBar
      backgroundColor={theme == 'Light' ? '#fff' : '#000'}
      barStyle={theme == 'Light' ? 'dark-content' : 'light-content'}
  />
  <ThemeContext.Provider value={themeData}>
    <NavigationContainer theme={theme == 'Light' ? CustomDefaultTheme : CustomDarkTheme}>
       <Drawer.Navigator
         screenOptions={{
           ...
         }}>
        ...
      </Drawer.Navigator>
    </NavigationContainer>
  </ThemeContext.Provider>
</SafeAreaView>
  • Related