React Native Finish Current Screen while Navigating to Next Screen

Introduction

While we navigate to the next screen from any screen the old screen remains in the stack and after coming back we see the same screen. React Native Finish Current Screen while Navigating to Next Screen includes how we navigate to the next screen and finish the old one from the stack?

Why do we need to finish the current screen while navigating to the next screen?

While developing an application there are some cases which need to change the screen without keeping the last screen. For example, If you have a Splash screen in your App which you want to show for the first time when the user opens the app and never want to show again either by pressing the back button or by any other way.

For this kind of cases we can use replace in place of navigate. As the name specifies replace prop will replace our current screen with the target screen provided as an argument.

navigation.replace('ThirdPage')

Let’s see how we can use replace.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

To navigate between screens we need to add react-navigation and other supporting dependencies.

To install the dependencies open the terminal and jump into your project

cd ProjectName

1. Install react-navigation

npm install @react-navigation/native --save

2. Other supporting libraries react-native-gesture-handler, react-native-reanimated, react-native-screens and react-native-safe-area-context and @react-native-community/masked-view

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save

3. For the Stack Navigator install

npm install @react-navigation/stack --save

Note: When you use a navigator (such as stack navigator), you’ll need to follow the installation instructions of that navigator for any additional dependencies. If you’re getting an error “Unable to resolve module”, you need to install that module in your project.

You might get warnings related to peer dependencies after installation. They are usually caused by incorrect version ranges specified in some packages. You can safely ignore most warnings as long as your app builds.

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install ios

To finalize the installation of react-native-gesture-handler, add the following at the top (make sure it’s at the top and there’s nothing else before it) of your entry files, such as index.js or App.js:

import 'react-native-gesture-handler';

Note: If you skip this step, your app may crash in production even if it works fine in development.

Project File Structure

To start with this Example you need to create a directory named pages in your project and create two files FirstPge.js and SecondPage.js in it.

Code

Now open App.js in any code editor and replace the code with the following code

App.js

// React Native Finish Current Screen while Navigating to Next Screen
// https://aboutreact.com/react-native-finish-current-screen-while-navigating-to-next-screen/

import 'react-native-gesture-handler';

import React from 'react';

import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';

import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';

const Stack = createStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="FirstPage">
        <Stack.Screen
          name="FirstPage"
          component={FirstPage}
          options={{
            title: 'First Page', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
        <Stack.Screen
          name="SecondPage"
          component={SecondPage}
          options={{
            title: 'Second Page', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

Open pages/FirstPage.js in any code editor and replace the code with the following code

FirstPage.js

// React Native Finish Current Screen while Navigating to Next Screen
// https://aboutreact.com/react-native-finish-current-screen-while-navigating-to-next-screen/

import React from 'react';
import {Button, View, Text, SafeAreaView} from 'react-native';

const FirstPage = ({navigation}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text
            style={{
              fontSize: 25,
              textAlign: 'center',
              marginBottom: 16,
            }}>
            This is the First Page of the app
          </Text>
          <Button
            title="Go to Second Sreen"
            onPress={() =>
              navigation.replace('SecondPage', {
                someParam: 'Some Param from previous Screen',
              })
            }
          />
        </View>
        <Text style={{textAlign: 'center', color: 'grey'}}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default FirstPage;

Open pages/SecondPage.js in any code editor and replace the code with the following code

SecondPage.js

// React Native Finish Current Screen while Navigating to Next Screen
// https://aboutreact.com/react-native-finish-current-screen-while-navigating-to-next-screen/

import React from 'react';
import {View, Text, SafeAreaView} from 'react-native';

const SecondPage = ({route}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{flex: 1, padding: 16}}>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text
            style={{
              fontSize: 25,
              textAlign: 'center',
              marginBottom: 16,
            }}>
            This is Second Page of the App
            {'\n'}
          </Text>
          <Text>{route.params.someParam}</Text>
        </View>
        <Text style={{textAlign: 'center', color: 'grey'}}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default SecondPage;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

ReactNativeFinishCurrentScreenWhileNavigatingtoNextScreen1   ReactNativeFinishCurrentScreenWhileNavigatingtoNextScreen2

Output in Online Emulator

This is how you can finish current screen while navigating to next screen in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

2 thoughts on “React Native Finish Current Screen while Navigating to Next Screen”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.