Search code examples
react-nativereact-navigationreact-navigation-stack

How to navigate to a screen on back button press in React navigation 5 stack navigator


There are many similar questions that have been answered but none of them uses the newest react-navigation version. I want to go to the 'Home' screen from the 'Document' screen on back button press. This is what I tried but it doesn't work.

<NavigationContainer>
  <Stack.Navigator initialRouteName="Home" screenOptions={{ headerShown : false }}>
    <Stack.Screen name="Home" component={Home} />
    <Stack.Screen name="Camera" component={CameraScreen} />
    <Stack.Screen name="Document" component={Document} options={{
      headerLeft: (props) => (<HeaderBackButton {...props} onPress={() => props.navigation.navigate("Home")}/>)
    }} />
  </Stack.Navigator>
</NavigationContainer>

Edit for more clarification: My app starts with 'Home' then goes to 'Camera' then to 'Document'. Now, I don't want to go back to 'Camera' once I am at 'Document' rather straight to 'Home' when I press the phone's back button. According to the documentation, this is how to override the back button.

<Screen
  name="Home"
  component={HomeScreen}
  options={{
  headerLeft: (props) => (
   <HeaderBackButton
     {...props}
     onPress={() => {
       // Do something
     }}
   />
 ),

}}/>; But I don't know how to go to 'Home' using the above code. So I searched similar questions and most of them had navigationOptions and other stuff. I tried following the below answer from a question.

import { HeaderBackButton } from 'react-navigation';
static navigationOptions = ({navigation}) => {
  return{
    headerLeft:(<HeaderBackButton onPress={()=>{navigation.navigate('A')}}/>)
}

} So yeah, the back button doesn't respond even if I use console.log


Solution

  • I managed to achieve what I needed. I had to override the physical back button in 'Document'.

     useFocusEffect(
            useCallback(() => {
              const onBackPress = () => {
                navigation.pop(2); // remove two screens i.e. Document and Camera
                return true // disable normal behaviour
              };
              BackHandler.addEventListener('hardwareBackPress', onBackPress); // detect back button press
              return () =>
                BackHandler.removeEventListener('hardwareBackPress');
            }, [])
          );