Search code examples
react-nativereact-navigationreact-native-navigationstack-navigator

How to navigate to other screen using the headerRight on the navigator code?


The title is very confusing, but the explanation that I will give will be more clear. I am creating one StackNavigator for my app, and I am defining one icon to be displayed on the header of one of my screens like so:

const navigator= createStackNavigator(
  {
    Initial: {
      screen: Posts,
      navigationOptions: {
        title: "All Posts",
        headerRight: () => {
          return (
            <TouchableOpacity style={{ padding: 5 }}>
              <Feather name={"plus"} size={30} />
            </TouchableOpacity>
          );
        },
      },
    },
    Details: Details,
    Create: Create,
  },
  {
    initialRouteName: "Initial",
  }
);

const App = createAppContainer(navigator);

export default () => {
  return (
    <Provider>
      <App />
    </Provider>
  );
};

The problem is that I want to navigate the user to the Create screen when the user presses the icon that I am rendering on the right side of the header, but I do not know how to have access to the navigation.navigate() function that the navigator generates for all the screens. I know that I can define the header on the Posts' screen file, so I have access to the navigation.navigate() function, but I want to know if there is some way to do it on the App.js file.

EDIT

Reading the documentation I saw that the way that I am was creating the navigator is not what the official documentation recommends. I learned to make it like this by one old course, using React Navigation 4.x, and now with React Navigation 6.x I perceived the difference in the creation and changed the way that I was doing it on my app. You can check the documentation for the problem that I was having here


Solution

  • You can prepare your navigation option this way by sending props

        options={(props) => ({
    headerRight: () =>  <TouchableOpacity 
                 onPress={()=>props.navigation.navigate('Screen')} style={{ padding: 5 }}>
                      <Feather name={"plus"} size={30} />
                    </TouchableOpacity>
                  })}