4

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?

Vivek Mahajan
  • 95
  • 1
  • 13
  • i usually keep a reference of the navigator, that way i can navigate from wherever i am,, check my answer here: https://stackoverflow.com/questions/62865226/how-to-access-navigation-prop-in-tabs-navigation-react-navigation/62873252#62873252 – Abdullah Asendar Aug 26 '20 at 12:34

2 Answers2

9

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

Sameer Kumar Jain
  • 2,074
  • 1
  • 13
  • 22
1

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}
        />
      ),

    })}
  />
Farhaan
  • 160
  • 2
  • 4