react-nativenavigation-drawerstack-navigatorreact-navigation-bottom-tab

React Native - Hide Drawer header in a stack that is inside a bottom tab navigator


I want to hide the header of drawer through all the screens of my form that is actually a stack. I'm working with React Native CLI.

Add Patient Stack

  <Stack.Navigator screenOptions={{headerShown: false}}>
      <Stack.Screen name="Step1" component={Step1} options={{headerShown: false}}/>
      <Stack.Screen name="Step2" component={Step2} options={{headerShown: false}}/>
  </Stack.Navigator>
<Tab.Navigator>
      <Tab.Screen  name="Home" component={HomeScreen} />
      <Tab.Screen  name="AddPatient" component={AddPatientStack} />
</Tab.Navigator>
 <Drawer.Navigator
      screenOptions={{header: () => <HeaderMenu />}}
      drawerContent={props => <CustomDrawerContent {...props} />}>
      <Drawer.Screen name="BottomTabNavigator" component={BottomTabNavigator} />
</Drawer.Navigator>

I've tried many things but nothing works.


Solution

  • You can use navigation.setOptions to toggle headerShown on and off for screens within the tab navigator. You'll want to do this in the component where you are creating the tab navigator; otherwise the navigation prop will reference the Stack navigator rather than the tab navigator:

    import { createMaterialBottomTabNavigator } from 'react-native-paper/react-navigation';
    import {
      getFocusedRouteNameFromRoute,
      useFocusEffect,
    } from '@react-navigation/native';
    import HomeScreen from './Home';
    import AddPatientStack from './AddPatient';
    const Tab = createMaterialBottomTabNavigator();
    
    const screensWithVisibleHeader = ['Home'];
    
    export default function BottomNavigator({ navigation, route }) {
      useFocusEffect(() => {
        const routeName = getFocusedRouteNameFromRoute(route);
        navigation.setOptions({
          headerShown: screensWithVisibleHeader.includes(routeName),
        });
      });
      return (
        <Tab.Navigator initialRouteName={'AddPatient'}>
          <Tab.Screen name="AddPatient" component={AddPatientStack} />
          <Tab.Screen name="Home" component={HomeScreen} />
        </Tab.Navigator>
      );
    }
    

    demo