react-nativereact-navigationreact-navigation-drawerreact-navigation-v6

Passing props to react navigation drawer custom header


How can I pass arguments to the following custom react navigation drawer header 'NavHeader'? I want to include an icon inside the NavHeader that uses the following: navigation.dispatch(DrawerActions.openDrawer())

function NavHeader(props) {
    return <View>...</View>;
}

<Stack.Navigator
  initialRouteName="Page1"
  screenOptions={{
    headerShown: true,
    headerTransparent:false,
    header: NavHeader
  }}
>
     <Stack.Screen name="Page1" component={Page1} />
     <Stack.Screen name="Page2" component={Page2} />
</Stack.Navigator>

Solution

  • The navigation object is in the props that get passed to NavHeader. Javascript syntax is hiding the arguments that get passed to your header; when passing a function, writing

    header: myFunction

    is the same as writing

    header: (args) => myFunction(args).

    In other words, your screenOptions could be rewritten like this:

      screenOptions={{
        // ...
        header: ({ navigation }) => <NavHeader navigation={navigation} />,
    

    This is why you can use the navigation object inside the NavHeader component. In your current NavHeader code, you can call it with props.navigation.

    Full props that get passed to the header:

    export type StackHeaderProps = {
      /**
       * Layout of the screen.
       */
      layout: Layout;
      /**
       * Options for the back button.
       */
      back?: {
        /**
         * Title of the previous screen.
         */
        title: string;
      };
      /**
       * Animated nodes representing the progress of the animation.
       */
      progress: SceneProgress;
      /**
       * Options for the current screen.
       */
      options: StackNavigationOptions;
      /**
       * Route object for the current screen.
       */
      route: Route<string>;
      /**
       * Navigation prop for the header.
       */
      navigation: StackNavigationProp<ParamListBase>;
      /**
       * Interpolated styles for various elements in the header.
       */
      styleInterpolator: StackHeaderStyleInterpolator;
    };