kwoxer
kwoxer

Reputation: 3833

navigation.navigate on a button in headerRight of the Stack Navigator

Firstly, I have the same issue as Button linking in headerRight. But their solution was simply using functional over component. I cannot simply switch to functional code as I need to use componentDidMount, so I really need solution for a component based headerRight navigation usage.

Stack

  function MyStack() {
    return (
      <Stack.Navigator>
        <Stack.Screen
          name="Root"
          component={BottomTabs}
          options={{
            headerRight: ({ navigation }) => (
              <View>
                <Button
                  onPress={() => navigation.navigate('Profile')}
                </Button>
              </View>
            ),
          }}
        />
        <Stack.Screen name="Profile" component={ProfileScreen} />
      </Stack.Navigator>
    );
  }

BottomTabs

const BottomTabs = createBottomTabNavigator();
function MyTabs() {
  return (
    <BottomTabs.Navigator
    ...

This will bring an error that navigation is not available there. Okay that's right, as you cannot use navigation directly in the definition of the Stack Navigator.

Even using:

headerRight: () => {
   return <ProfileButtonScreen/>
}, 

did not help as on that component I still not have the navigation available.

This is too less info but is already going in the right direction. And finally this gave me the idea about misusing the BottomTabs for the defining of the headerRight.

Upvotes: 0

Views: 464

Answers (1)

kwoxer
kwoxer

Reputation: 3833

Stack

  function MyStack() {
    return (
      <Stack.Navigator>
        <Stack.Screen
          name="Root"
          component={BottomTabs}
        />
        <Stack.Screen name="Profile" component={ProfileScreen} />
      </Stack.Navigator>
    );
  }

BottomTabs

const BottomTabs = createBottomTabNavigator();
function MyTabs({ navigation, route }) {
  navigation.setOptions({
    headerRight: () => (
      <View>
        <Button
          onPress={() => navigation.navigate('Profile')}
          title="To Profile"
        >
        </Button>
      </View>
    ),
  });

  return (
    <BottomTabs.Navigator
    ...

This will now let you have a clickable button on stack navigation header.

clickable button on stack navigation header

Upvotes: 2

Related Questions