How to finish current component while navigating to next component in react native

react-navigation close current screen
react native navigation example
react native navigation goback with params
react-navigation example
react navigation 4
react-navigation, screenprops
react native go back to previous screen
react-native get current screen

Hi I am trying to navigate to next component using navigate function. I am using react-navigation for the navigation among multiple components.

Suppose I have index.android.js and DashboardScreen.js component. I am trying to navigate to DashboardScreen.js component from index component.

It is navigating but index component always retain in component stack. when I press back then it opens index.android.js which should not be. Does anyone know how to manage this in react-native. In Android, finish() works for this.

navigate("DashboardScreen");

When I am navigating from SplashScreen to EnableNotification then SplashScreen should be destroyed, if I am navigating from EnableNotification to CreateMessage then EnableNotification should be destroyed and if I am navigating from CreateMessage to DashboardScreen then CreateMessage should be destroyed. As of now no component is being destroyed.

index.android.js

class SplashScreen extends Component {
  render() {
    if (__DEV__) {
      console.disableYellowBox = true;
    }

    const { navigate } = this.props.navigation;

    AsyncStorage.getItem("@ProductTour:key").then(value => {
      console.log(value);
      if (value) {
        navigate("DashboardScreen");
      }
    });

    return (
     ....
    );
  }
}

const App = StackNavigator(
  {
    Splash: {
      screen: SplashScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    EnableNotification: {
      screen: EnableNotificationScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    CreateMessage: {
      screen: CreateMessageScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    DashboardScreen: {
      screen: DashboardScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    }
  },
  {
    initialRouteName: "Splash"
  }
);

Just use 'replace' in place of 'navigate'

this.props.navigation.replace('Your Next Component Name')

React Native Finish Current Screen while Navigating to Next Screen , App.js. //This is an example of Finish Current Screen while Navigating to Next Screen// import React, { Component } from 'react'; //import react in our code. import  To finish the current screen while navigating to the next screen you have to define the navigation of the screen by the createSwitchNavigator in place of createStackNavigator. It will not store your previous screen into the stack so the user will not be able to go to the previous screen.

First of all, using AsyncStorage in an a synchronous function (most especially a lifecycle one) is such a bad idea. You should typically keep ASyncStorage to places in your folder / app structure that make sense for where you access/keep data but since that's not the question I will just mention it quickly here...

Basically you are asking to navigate once the ASync method completes itself based on EVERY render... Those new to RN should know that an awful lot of things can cause a render to fire. Some cases, the render function can fire (I have seen this many times before) 10 or more times before finalizing the last render. This means you would have fired that ASyncStorage method 10 times... definitely something to think about when implementing this stuff. So more or less, the .then(); part of the AsyncStorage function is firing long after the render has already finished doing it's thing. If it was a reasonable approach to use I would say to put the return part of the render function inside of the .then((value) => { return ( ... ); });. But this is an even worse idea. Basically you need the right lifecycle method here and it's NOT the render method.

Anyway, since I have never used this component library before I can only help nudge you in the right direction so here goes... These docs on their webpage seem to say that you need a reference to the props navigator passed down to the component in which you are using it. So if you created the navigator in this class, you would use this.refs.whateverYouNamedTheNavigatorReference.navigate('SomeItemName'). If you are in the class that has been passed this navigator as a prop, you use this.props.passNavigatorPropName.navigate('SomeItemName'). I see you are using variable deconstruction to get the navigate callback but I would caution on doing this, this way because I have seen it cause errors by grabbing an old version of the navigate function or its parent reference by accident and causing a cascading error effect.

Also, if you are going to be using ASyncStorage in a component file (again, would recommend putting this in a component/class where your data is accessed throughout the app...) and you are going to use it to decide the app should navigate forwards/backwards... definitely remove it from the render function and put it in maybe the constructor, componentWillReceiveProps, componentDidReceiveProps or componentWillUpdate lifecycle functions. That way it fires based on an update, a new passed prop obj or one time as the component is built. Anything is better than firing it every single render.

Lastly, I do not know what you have setup for your StackNavigator route stack object but you would need to have the keyword you used "DashboardScreen" in there pointing to an actual component that has been imported properly. The "DashboardScreen" keyword most likely would connect in your StackNavigator object to some component import like so...

import Dashboard from '../Views/DashboardScreenView';

StackNavigator({
  DashboardScreen: {
    screen: Dashboard,
    path: 'dashboard/:main',
    navigationOptions: null,
  },
});

Refresh Previous Screen after Going Back in React Navigation, While switching between screens sometimes we want to refresh the previous In this case, we will also use a listener called didFocus to find the current react-​native init ProjectName --version react-native@next //Example to Refresh Previous Screen When Going Back in React Navigation// import React, { Component }  Contents in this project Finish Current Activity Route Screen Navigate to Next using createSwitchNavigator Example Tutorial in React Native Android iOS App: 1. The most important step is the install the React Navigation library into our current react native project so we can use its inbuilt createSwitchNavigator component. So to install the react navigation library open your react native project folder in command prompt / terminal and execute below command.

There is a simple way here: use "replace" (reference link repleace in navigation ,For example, you are at the screen "Login" , and you want to move to screen "Home", insert this code in screen "Login"

                         <TouchableOpacity onPress={() => { this.login() }}>

                            <Text}>Click me to Login</Text>

                        </TouchableOpacity>

and method login:

login(){
  this.props.navigation.replace('Home')
 }

Screen "Login" will be replaced by "Home", in Android, press Back Button =>app exit, no back screen "Login"

React Native Finish Current Activity Route Screen Navigate to Next , React Native Finish Current Activity Route Screen Navigate to Next using kill the current activity and then navigate to another so when application Import the createSwitchNavigator component from react navigation library. This guide covers the various navigation components available in React Native. If you are getting started with navigation, you will probably want to use React Navigation . React Navigation provides a straightforward navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both Android and iOS.

Based on your requirement, i suggest following setup:

SplashNavigator.js

const SplashNavigator = StackNavigator({
  Splash: {
    screen: SplashScreen,
    navigationOptions: {
      header: {
        visible: false
      }
    }
  }
});

AppNavigator.js

const AppNavigator = StackNavigator(
  {
    EnableNotification: {
      screen: EnableNotificationScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    CreateMessage: {
      screen: CreateMessageScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    Dashboard: {
      screen: DashboardScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    }
  },
  {
    initialRouteName: "EnableNotification"
  }
);

In your index.android.js, you will render the SplashNavigator.

The SplashNavigator will render the SplashScreen. It has initial state value isReady set to false, so it will render a loading text until the @ProductTour:key value from AsyncStorage is loaded (AsyncStorage is async function, u should not put it in your render function). It will then render your AppNavigator and render your EnableNotification as initial route.

class SplashScreen extends Component {
  constructor() {
    super(props);
    this.state = {
      isReady: false,
    }
  }

  componentDidMount() {
    AsyncStorage.getItem("@ProductTour:key").then(value => {
      console.log(value);
      // you will need to handle case when `@ProductTour:key` is not exists
      this.setState({
        isReady: true,
      });
    });
  }

  render() {
    const { isReady } = this.state;
    return (
      <View style={{flex: 1}}>
        {
          isReady ?
          <AppNavigator />
          : <Text>Loading</Text>
        }
      </View>
    );
  }
}

Then on EnableNotificationScreen and CreateMessageScreen, change your navigate route function to use NavigationActions.reset from doc

Example:

import { NavigationActions } from 'react-navigation';

handleOnPressButton = () => {
  const resetAction = NavigationActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({ routeName: "CreateMessage" })
    ]
  });
  this.props.navigation.dispatch(resetAction);
}

Navigating Between Screens or Activities Using React Navigation , to the stack navigator even if already present in the stack. this.props.navigation. Add react-navigation in package.json file in react native application. This component will be the home screen or default screen. when user launch this Lets see the complete source code that helps to Navigating Between Screens or​  Next, install the following dependencies for the react-navigation library to work. The first command is going to install the core utilities of react-navigation that are used by navigators to create the navigation structure in the app. The second command uses expo install instead of npm install or yarn add.

this.props.navigation.replace('Your Next Component Name')

How to navigate to a new screen and close the current screen , I'm new in React Navigation. I've researched many navigators (StackNavigator) but I did not find an example for my case. For example, I'm in  You can go back to an existing screen in the stack with navigation.navigate('RouteName'), and you can go back to the first screen in the stack with navigation.popToTop(). The navigation prop is available to all screen components (components defined as screens in route configuration and rendered by React Navigation as a route).

Routing with React Navigation in React Native, A brief introduction to routing using the React Navigation library for React Native. While this tutorial has content that we believe is of great benefit to our Next, create a file called AppNavigator.js : In App.js , add an array of possible friends and an array of current friends to the component's state: App.js. React Navigation's stack navigator provides a way for your app to transition between screens and manage navigation history. If your app uses only one stack navigator then it is conceptually similar to how a web browser handles navigation state - your app pushes and pops items from the navigation stack as users interact with it, and this results in the user seeing different screens.

Moving between screens, import { NavigationContainer } from '@react-navigation/native'; navigation - the navigation prop is passed in to every screen component The header provided by stack navigator will automatically include a back button when it is possible Next. Passing parameters to routes ». Navigating to a new screen; Navigate to a​  react-native-screens. This project aims to expose native navigation container components to React Native. It is not designed to be used as a standalone library but rather as a dependency of a full-featured navigation library.

Getting Started with Stack Navigator Using react-navigation 5 in , Next, install the following dependencies for the react-navigation library to work. This function returns two React components: Screen and Navigator , which help In the current stack navigator structure, let's add the second screen The default native transition on iOS when using stack navigation is that  The Link component provided by react-router-dom helps in creating a anchor tags which will navigate without re-loading the page itself. If we use the default anchor tag provided by html, it will reload the page while navigating. But as we have only one page index.html and we are just navigating to other jsx component we don’t the page reloads.

Comments
  • Thanks. Suppose I have one component EnableNotification from which I am calling navigate("CreateMessage") to open CreateMessage component. It is starting a component but not finishing EnableNotification component. This is what I am looking. Whats way to destroy EnableNotification
  • BTW Your suggestions are really appreciable. I don't know how to declare AsyncStorage in other js file and use it in my component ? can you add some snippet line of code ?
  • sorry. i think it is the question which actually misleading. it should be specified as "in AsyncStorage callback". but perhaps it's not the issue he had. i don't know whether it is better to put your answer as an answer or as a comment. because your answer is focusing on "within AsyncStorage callback" scope
  • the real answer is to use navigation.dispatch. it's confusing why you didn't mention it. i think it's good to consider this is an old issue
  • because I was not familiar with the package this person was using and could only offer obvious observations in which 4 other people found useful enough to upvote. It is not the selected answer.
  • Thanks @alpha. I think some points are still missing. Suppose I have one component EnableNotification from which I am calling navigate("CreateMessage") to open CreateMessage component. It is starting a component but not finishing EnableNotification component. This is what I am looking. Whats way to destroy EnableNotification
  • @Williams I don't quite get your question, can you tell us what is your navigation flow and how user navigate to EnableNotification screen.
  • It starts with SplashScreen -> EnableNotification -> CreateMessage -> DashboardScreen. I have button on each component and on clicking on it I am calling navigate(name_of_the_component. It works but components are not being destroyed.
  • @Williams So what you want is like step wizard, user cannot navigate back after user navigated to DashboardScreen, am I correct?
  • Nope. When I am navigating from SplashScreen to EnableNotification then SplashScreen should be destroyed, if I am navigating from EnableNotification to CreateMessage then EnableNotification should be destroyed and if I am navigating from CreateMessage to DashboardScreen then CreateMessage should be destroyed. As of now no component is being destroyed
  • Please elaborate shortly what this line does and why it helps to solve the problem.