SoldierCorp
SoldierCorp

Reputation: 7700

React Navigation 3: Back button in Android doesn't back to previous screen

I am upgrading my router configuration of my React Native app using React Navigation 3 and many things has been improved now but I don't understand why when I press the back button in Android, is not sending me to the previous view and instead is sending me to the Home one.

My routes

const drawerConfig = {
  initialRouteName: 'Home',
  contentComponent: SideMenu,
  drawerWidth: width,
}

const MainDrawerNavigator = createDrawerNavigator(
  {
    Home: {
      screen: Home,
    },
    Company: {
      screen: Company,
    },
    Gifts: {
      screen: Gifts,
    },
    Jobs: {
      screen: Jobs,
    },
    Job: {
      screen: Job,
    },
    Contact: {
      screen: Contact
    }
  },
  drawerConfig,
);

const InitialStack = createStackNavigator(
  {
    Menu: {
      screen: Menu,
      path: 'menu/',
    }
  },
  {
    initialRouteName: 'Menu',
    headerMode: 'none',
  }
);

const SwitchNavigator = createSwitchNavigator(
  {
    Init: InitialStack,
    App: MainDrawerNavigator,
  },
  {
    initialRouteName: 'Init',
  }
);

const AppContainer = createAppContainer(SwitchNavigator);

export default AppContainer;

If I do this: Open Drawer, open Jobs then press in a job button to load the Job view the flow is working well but If I press the back button in the Job view is not showing the Jobs but the Home.

I am navigation using this.props.navigation.navigate('...') because the push is not working.

Do you know why?

I am using react-navigation 3.5.1 and react-native 0.59.3

Upvotes: 3

Views: 1717

Answers (2)

SoldierCorp
SoldierCorp

Reputation: 7700

I just figured out.

I was not writing the right configuration for my routes because if I wanted to back from Job to Jobs instead to Home, a stack was necessary for every "stack" of views I needed, so now they can work exactly how I want, the pop is working great without using the back handler event.

Like this:

// Jobs stack
const JobsStack = createStackNavigator(
    {
        JobList: {
            screen: Jobs,
        },
        Job: {
            screen: Job,
        },
    },
    {
        headerMode: 'none',
    }
);

// Main drawer
const MainDrawerNavigator = createDrawerNavigator(
    {

        ...
        Jobs: JobsStack,
        Contact: {
            screen: Contact
        }
        ...
    },
    drawerConfig,
);

Thank you to all the people that helped me :)

Upvotes: 2

ahd786
ahd786

Reputation: 195

You can import BackHandler from 'react-native' and can use the code like below in your screen class from where you want to go back:

componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}

componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}

handleBackButton = () => {
    this.props.navigation.goBack();
    return true;
};

Upvotes: 0

Related Questions