How to access the navigation prop in the Stack Navigator's screenOptions attribute?

Viewed 2306

I want to navigate to a particular screen using a common header button in the stack navigator.

 <NavigationContainer>
  <RootStack.Navigator 
    mode="modal"
    screenOptions={{
      headerTitleAlign: 'center',
      headerTitle: () => <SpreeLogo />,
      headerRight: (props) => <MaterialIcons style={{
        marginHorizontal: 10,
      }}
      onPress={() => console.log(props)}
      name="clear" size={28} color="black" />
    }}
  >

In the header right icon I would like to have access to the navigation prop. I've tried console logging the prop but there is no prop as navigation. How to get access to it?

2 Answers

As per documentation you can provide a function to screenOptions like below which will give you access to the navigation and from there you should be able to jump to any screen

<NavigationContainer>
  <RootStack.Navigator 
    mode="modal"
    screenOptions={({ route, navigation }) => ({
      headerTitleAlign: 'center',
      headerTitle: () => <SpreeLogo />,
      headerRight: (props) => <MaterialIcons style={{
        marginHorizontal: 10,
      }}
      onPress={() => console.log(route, navigation)}
      name="clear" size={28} color="black" />
    })}
  >...

Read the docs here https://reactnavigation.org/docs/stack-navigator and search for screenOptions.

Good Luck

In React Navigation V6 you can provide a function to options

<Stack.Screen
    name="Screen"
    component={Screen}
    options={({ route, navigation }) => ({
      headerTitleAlign: "center",
      headerLeft: () => (
        <Icon
          name="arrow-back"
          onPress={() => navigation.goBack()}
          color="#fff"
          size={25}
        />
      ),

    })}
  />
Related