Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finish current component while navigating to next component using React Native Navigation?

I wanted to close the current component completely while navigating to next component in react-native.

I am using react-navigation for navigating between screens.

Scenario is, I am having two js in my project, Login.js and Home.js. When user logs in into the app it saves the credentials in the AsyncStorage. Every-time when user comes to Login Screen it checks for whether user is logged in already or not. If the user is logged in then app will directly navigate you to the Home page, at this action I want to close the login screen completely.

Currently with my implementation the Login screen remains in to the navigation stack. When I press back from the Home page the app should be closed completely and should not relaunch with login screen again.

Here is my StackNavigator code :

const navigationStack = createStackNavigator(
  {
    Login: {
      screen: LoginScreen
    },
    Home: {
      screen: HomeScreen
    },
  },
); 

For navigating :

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

Please let me know what I am doing wrong with my existing code?

like image 783
amol anerao Avatar asked May 15 '18 08:05

amol anerao


1 Answers

You can implement this by multiple ways. Like using replace or reset action on stack Navigator, or using switch Navigator instead of stack Navigator.

Using Reset: (Empty stack and navigate to specified screen)

import { StackActions, NavigationActions } from 'react-navigation';

const resetAction = StackActions.reset({
 index: 0,
 actions: [NavigationActions.navigate({  routeName: 'Home' })],
});


this.props.navigation.dispatch(resetAction);

Using replace: (replace current screen with the specified screen)

this.props.navigation.replace("Home");

Using Switch Navigator:(Recommended)

const navigationStack = createSwitchNavigator(
  {
    Login: {
      screen: LoginScreen
    },
    Home: {
     screen: HomeScreen
    },
  },
); 

// Navigate to screen
this.props.navigation.navigate("Home");
like image 180
Swapnil Avatar answered Oct 19 '22 19:10

Swapnil