Amit Kahlon
Amit Kahlon

Reputation: 118

How can I add navigation in the navigation header?

I'm trying to create a button for navigating to "CreateScreen", the button is placed in the header so I wrote it inside <NavigationContainer> as the documentation suggested, but it seems I don't have access to navigation, I don't actually need it inside NavigationContainer, so if you have other suggestions for implementing(for example, implementing the button inside the component) it will be great.

That's What I'm trying to accomplish(part of app.js)

headerRight: () => {
            return <TouchableOpacity>
              <Feather name="plus" size={30} onPress={() => navigation.navigate('Create')} />
            </TouchableOpacity>
const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Index">
        <Stack.Screen
          name="Index"
          component={IndexScreen}
          options={{
            title: 'Home',
            headerRight: () => {
              return (
                <TouchableOpacity>
                  <Feather
                    name="plus"
                    size={30}
                    onPress={
                      () => navigation.navigate('Create')
                      //Thats what Im trying to accomplish
                    }
                  />
                </TouchableOpacity>
              );
            },
          }}
        />
        <Stack.Screen name="Show" component={ShowScreen} />
        <Stack.Screen name="Create" component={CreateScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Upvotes: 1

Views: 116

Answers (2)

Anhdevit
Anhdevit

Reputation: 2104

In option will return navigation

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Index">
        <Stack.Screen
          name="Index"
          component={IndexScreen}
          //navigation<<<<<<<<<<<<<<<<<<<<<<<<<here
          options={({navigation, route}) => ({
            title: 'Home',
            headerRight: () => {
              return (
                <TouchableOpacity>
                  <Feather
                    name="plus"
                    size={30}
                    onPress={() => navigation.navigate('Create')}
                  />
                </TouchableOpacity>
              );
            },
          })}
        />
        <Stack.Screen name="Show" component={ShowScreen} />
        <Stack.Screen name="Create" component={CreateScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Upvotes: 0

Wen W
Wen W

Reputation: 2647

you can use the useNavigation hook to gain access to the navigation prop:

import { useNavigation } from '@react-navigation/native';

const navigation = useNavigation();
navigation.goBack();

source: https://reactnavigation.org/docs/use-navigation/

Upvotes: 1

Related Questions