Search code examples
react-nativereact-navigationreact-navigation-stackreact-navigation-drawer

Back header button in drawer navigation


How can i have a back button on some screen eg ProfileScreen/ReporterScreen such that clicking on it would take user to ContentFlow.

const ProfileNavigator = createStackNavigator({ ProfileScreen });
const ReporterNavigator = createStackNavigator({ ReporterScreen });

const ContentNavigator = createMaterialBottomTabNavigator({ ContentScreen });

const HomeNavigator = createDrawerNavigator({
 ContentFlow:ContentNavigator,
 ProfileFlow:ProfileNavigator,
 ReporterFlow:ReporterNavigator
});

I have added header button for drawer in ContentScreen, but for other screens i want to have back button instead, how to navigate to ContentFlow, when back button is pressed.


Solution

  • You can set headerLeft to a component in the navigationOptions. So for example if you want to have one or more screens inside ReporterNavigator that have a header button that allows a user to navigate to ContentFlow you could do something like this:

    const ReporterNavigator = createStackNavigator({
      Screen: {
        screen: ScreenComponent,
        navigationOptions: ({ navigation }) => {
          return {
            headerLeft: () => (
              <Button
                title="go to contentflow"
                onPress={() => {
                  navigation.navigate('ContentFlow');
                }}
              />
            ),
          };
        },
      },
    });
    

    If you want to have the button for all screens of the ReporterNavigator you will want to use defaultNavigationOptions instead of navigationOptions. Keep in mind that navigationOptions are set inside the RouteConfigs and defaultNavigationOptions are defined in the NavigatorConfigs (https://reactnavigation.org/docs/4.x/stack-navigator/#stacknavigatorconfig).


    When you do this:

    const HomeNavigator = createDrawerNavigator({
      ContentFlow: ContentNavigator,
      ProfileFlow: ProfileNavigator,
      ReporterFlow: ReporterNavigator,
    });
    

    the navigation object also gets passed down. Because it gets passed down from the drawer navigator it holds its navigation state of that navigator. So you are able to navigate to screens inside the drawer navigator.

    If you wanted to access the navigation state of the ReporterNavigator you could instead access the props in the anonymous function headerLeft is set to:

    // ...
    headerLeft: ({navigation}) => (
      // etc...
    )
    // ...