Home > Software engineering >  React Native - navigation on top right header button
React Native - navigation on top right header button

Time:04-27

A screen of my app (FeedScreen) has a top-right header button. I want that button to navigate to another screen on press.

This is my code:

const Stack = createNativeStackNavigator();

function App({ navigation }) {
return (
  <>
  <StatusBar hidden />
  <NavigationContainer>
    <Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Login" component={LoginScreen} />
      <Stack.Screen name="Signup" component={SignupScreen} />
      <Stack.Screen name="TestScreen" component={TestScreen} />
      <Stack.Screen name="CarouselScreen" component={CarouselScreen} />
      <Stack.Screen name="SettingsScreen" component={SettingsScreen} />
      <Stack.Screen name="InsertNumberScreen" component={InsertNumberScreen} />
      <Stack.Screen name="FeedScreen"
       component={FeedScreen}
       options={{
        title: 'My screen',
        headerStyle: {
          backgroundColor: '#262423',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
          fontWeight: 'bold',
        },
        headerRight: () => (
          <Button
            onPress={() => navigation.navigate('UploadPictureScreen')}
            title=" "
            color="#fff"
          />
        ),
      }} 
      />
      <Stack.Screen name="UploadPictureScreen" 
        component={UploadPictureScreen} 
        options={{
          title: 'Upload a picture',
          headerStyle: {
            backgroundColor: '#262423',
          },
          headerTintColor: '#fff',
          headerTitleStyle: {
            fontWeight: 'bold',
          },
        }}
      />
    </Stack.Navigator>
  </NavigationContainer>
  </>
);
}

Unfortunately, it returns "Undefined is not an object (evaluating 'navigation.navigate')".

CodePudding user response:

I think this should work, let me know if it doesn't


    <Stack.Screen
            name="FeedScreen"
            component={FeedScreen}
            options={({ route, navigation }) => ({
              title: "My screen",
              headerStyle: {
                backgroundColor: "#262423"
              },
              headerTintColor: "#fff",
              headerTitleStyle: {
                fontWeight: "bold"
              },
              headerRight: () => (
                <Button
                  onPress={() => navigation.navigate("UploadPictureScreen")}
                  title=" "
                  color="#fff"
                />
              )
            })}
          />

  • Related