Change background color of top bar when navigation drawer is opened

Viewed 867

I am developing a react-native project. My screens are in white color, but navigation drawer from left in dark grey color, I would like to have the top bar part of the screen also show dark grey when the drawer is opened but still show white when drawer is closed, how to achieve that?

I am using "@react-navigation/drawer": "^5.8.6" for my drawer:

<Drawer.Navigator
    initialRouteName={InitialScreen}
    drawerContent={props => <MyDrawer {...props} />}
    screenOptions={{
        headerShown: true,
    }}>
    <Drawer.Screen name="main" component={MainScreen} />
</Drawer.Navigator>

As you can see I am using my custom layout for the drawer content <MyDrawer />, there, I set background to dark grey.

The following screenshot shows how it looks like at the moment when drawer is opened. enter image description here

1 Answers

I think you can use this hook (Drawer hook) and the react-native <StatusBar /> (React native status bar) to have it changed easily. Something like that :

const Drawer = createDrawerNavigator()

export function Screen(props) {
  const isDrawerOpen = useIsDrawerOpen()
  return (<>
    <StatusBar backgroundColor={isDrawerOpen ? colors.darkGrey : colors.white}/>
    {props.children}
  </>)
}

export function MainScreen(props) {
  return (
    <Screen>
      ...
    </Screen>
  )
}

export function test() {
  return (
    <>
      <Drawer.Navigator
        initialRouteName={InitialScreen}
        drawerContent={props => <MyDrawer {...props} />}>
        <Drawer.Screen name="main" component={MainScreen} />
      </Drawer.Navigator>
    </>
  )
}
Related