Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 883
Wai Yan Hein Avatar asked Jun 08 '19 11:06

Wai Yan Hein


People also ask

How do I clear react navigation stack?

To reset the navigation stack for the home screen with React Navigation and React Native, we can use the navigation. dispatch and the CommonActions. reset methods. import { CommonActions } from "@react-navigation/native"; navigation.


1 Answers

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.

like image 61
Hardik Virani Avatar answered Sep 18 '22 14:09

Hardik Virani