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

React Native clear the previous screen from the navigation stack


I am developing a React native application for learning purposes. I am now implementing navigation using React Navigation. I am using stack navigation. But I cannot find a way to remove the previous screen from navigation history and kill the app.

I set up my navigation like this.

const AppStack = createStackNavigator({
  Login: {
    screen: Login
  },
  Register: {
    screen: Register
  },
  Events: {
    screen: Events
  }
});

As you can see in the above code, I open the log in screen by default. After login, I open the Events screen like this.

this.props.navigation.navigate('Events');

The problem is that, When I am on the events page, I can see the back button in the navigation bar. When I press on it, I was brought back to the sign in page.

But what I want is that, after login, I want to remove the sign-in page from the stack. When I am on the events page, when I click on the back button, the app should be closed. Maybe it might not have the back button. It will just act like a first screen in that case. How can I do that?


Solution

  • When Login or Register is completed successfully you have to reset your navigation stack like below,

    import { StackActions, NavigationActions } from 'react-navigation';
    const resetAction = StackActions.reset({
        index: 0,
        actions: [NavigationActions.navigate({ routeName: 'Events' })],
    });
    this.props.navigation.dispatch(resetAction)
    

    and additionally in your Event page you have to add one static method if you don't want header there.

    static navigationOptions = navigation => ({
            header: null
    });
    

    Hope it will help you.