Navigate Between Screens using React Navigation V6 in React Native

React Navigation

This example will help you to learn how to navigate between screens using React Navigation in React Native App. React Navigation is not the only option for routing and navigation between screens in React Native. If you want to explore other options then you can also see the listed libraries below.

  • react-native-router-flux: This library is based on React Navigation but provides you some different APIs to interact with it.
  • react-native-navigation: It uses the underlying native APIs on iOS and Android, this is a popular alternative to React Navigation.

I have worked with React Navigation and react-native-navigation. These both libraries are good but when we talk about the customization then react-native-navigation provides you fewer options for customization that is why I personally like React Navigation. React Navigation is also suggested by the React Native team and has very good performance also.

In this example, we will use react-navigation library for the Navigation between screens. React Native Navigation can be used to switch from one screen to another in the desired manner. This navigation solution is written entirely in JavaScript (so you can read and understand all of the sources), on top of powerful native primitives.

How to Navigate Between Screens

React Navigation provides all the different type of navigator like

  1. Stack navigator: For the simple screen switching
  2. Drawer Navigator: To create Navigation Drawer/ Sidebar
  3. Bottom Tab Navigator: For the bottom navigation
  4. Top Tab Navigator: To create the tab navigation

I am going to show simple navigation in this example so we will see Stack navigator (createNativeStackNavigator) to navigate using React Navigation. For the stack navigation we need to do the following thing:

1. Installation of React Navigation Library (Which we will see below)

2. Setup NavigationContainer which is an index of the app. Here you list all the screens as a component and provides the name to them.

<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}/>
    <Stack.Screen name="ThirdPage" component={ThirdPage}/>
  </Stack.Navigator>
</NavigationContainer>

If you see in the above code snippet I have created an NavigationContainer which has our stack navigator defined.

In this stack navigator, we will have each of the app screens as a Stack.Screen. We can keep the name different from the component name as we will use the name as a reference for that component. It is because if you have any update in any component then you can change the component in the index and everything will be ok, nothing will break as we have used the name(reference) to switch to that component.

If you noticed we have an option prop also which allows you to customize your header options like title, background color, text color, style, and more. You can also use the custom header instead of the default header.

One more thing to highlight is the initialRouteName which defines the landing screen of the app when the user opens the app.

3. Once we set our NavigationContainer we can now use our name references to switch to any of the screens we want. We can switch the screen using

navigation.navigate('SecondPage')

This means we want to switch to the component which has the name SecondPage and it will navigate you to component with the name SecondPage.

Stack Navigator

Stack Navigator is used to moving/navigate between screens. It is called Stack navigator because while doing navigation it managed the stack of the screens. For example, If I have FirstPage, SecondPage, and ThirdPage and I am moving from FirstPage to SecondPage then it will keep the FirstPage in the stack and after moving to ThirdPage it will keep FirstPage and SecondPage in the stack. Once we request to go back to the previous screen it will pull the last inserted screen form the stack and show it in front, so in case of ThirdPage, we will see SecondPage and from SecondPage we will see FirstPage.

With the help of navigation, we can perform a different type of switching operations like

1. Navigating to new screen

navigation.navigate('SecondPage')
  • navigation – the navigation prop is passed into every screen component in stack navigator
  • navigate(‘SecondPage’) – we call the navigate function with the name of the route that we’d like to move the user to.

If we call navigation.navigate with a route name that we haven’t defined on a stack navigator, nothing will happen.

2. Navigate to a route multiple times

If you have any situation where you are on the SecondPage and have to open SecondPage again then you will see making navigation.navigate('SecondPage') the route will do nothing. It also makes sense for the normal case that why anybody wants to switch to the same screens? but for the special cases, they have provided navigation.push

navigation.push('SecondPage')

push allows us to express the intent to add another route regardless of the existing navigation history. So even if you are on SecondPage you can push the SecondPage again.

3. Going back

The header provided by the stack navigator will automatically include a back button when it is possible to go back from the active screen (If there is only one screen in the navigation stack, there is nothing that you can go back to, and so there is no back button).

Sometimes you’ll want to be able to programmatically trigger this behavior, and for that, you can use

navigation.goBack();

4. Go back to the first screen in the stack

If you want to go back to multiple screens, for example, if you are several screens deep in a stack and want to dismiss all of them to go back to the first screen of the stack then you can use

navigation.popToTop()

This will discard all the screens of the stack and will take you to the first screen in the stack.

5. Replace Screen In Stack

There are some cases which need to change the screen without keeping the last screen. For example, I have navigated to SecondPage from FirstPage and then want to navigate to ThirdPage but without keeping SecondPage in the Stack then I can use

navigation.replace('ThirdPage')

This will replace the SecondPage with the ThirdPage and will not keep SecondPage in the stack which means when we go back form the ThirdPage we will see FirstPage instead of the SecondPage.

6. Reset Navigator State

This is a bit different thing as all the above-mentioned navigation functions are to manage the different types of navigations but this function will help you to reset your navigation state in runtime. For example, If you want to land the user on different screens on the basis of different permissions then you can use this to reset the navigator.

navigation.reset({
    index: 0,
    routes: [{ name: 'ThirdPage' }],
})

Here I have reset the ThirdPage as an initial page of the stack.

Project Overview

In this example, I have tried to cover most of the different types of navigation possible in the Stack Navigator. If we talk about the project then the final example will have three screens which will help us to understand the above-mentioned navigations.

Let’s get started with the app creation, dependencies installation, and code understanding.

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 command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

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

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

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

Installation of Dependencies

To navigate between screens using React Navigation 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-screens and react-native-safe-area-context

npm install react-native-screens react-native-safe-area-context --save

react-native-screens package requires one additional configuration step to properly work on Android devices. Edit MainActivity.java file which is located in android/app/src/main/java/<your package name>/MainActivity.java.

Add the following code to the body of MainActivity class:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(null);
}

and make sure to add the following import statement at the top of this file below your package statement:

import android.os.Bundle;

This change is required to avoid crashes related to View state being not persisted consistently across Activity restarts.

3. For the Stack Navigator install

npm install @react-navigation/native-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

Directory Structure for Example

To start with this Example you need to create a directory named pages in your project and three files under it with the name FirstPage.js, SecondPage.js, and ThirdPage.js

StackNavigationStructure

Code to Navigate Between Screens using React Navigation

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

App.js

// Navigate Between Screens using React Navigation in React Native //
// https://aboutreact.com/react-native-stack-navigation //

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

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

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

const Stack = createNativeStackNavigator();

function 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.Screen
          name="ThirdPage"
          component={ThirdPage}
          options={{
            title: 'Third 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;

pages/FirstPage.js

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

// Navigate Between Screens using React Navigation in React Native //
// https://aboutreact.com/react-native-stack-navigation //
import * as 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
            onPress={() => navigation.navigate('SecondPage')}
            title="Go to Second Page"
          />
        </View>
        <Text style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey'
          }}>
          Navigate Between Screens using
          {'\n'}
          React Navigation
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey'
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
}

export default FirstPage;

pages/SecondPage.js

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

// Navigate Between Screens using React Navigation in React Native //
// https://aboutreact.com/react-native-stack-navigation //
import * as React from 'react';
import { Button, View, Text, SafeAreaView } from 'react-native';

const SecondPage = ({ 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 Second Page of the App
          </Text>
          <Button
            title="Go back"
            onPress={() => navigation.goBack()}
          />
          <Button
            title="Go to SecondPage... again"
            onPress={() => navigation.push('SecondPage')}
          />
          <Button
            title="Replace this screen with Third Page"
            onPress={() =>
              navigation.replace('ThirdPage', {
                someParam: 'Param',
              })
            }
          />
          <Button
            title="Reset navigator state to Third Page"
            onPress={() =>
              navigation.reset({
                index: 0,
                routes: [
                  {
                    name: 'ThirdPage',
                    params: { someParam: 'reset' },
                  },
                ],
              })
            }
          />
          <Button
            title="Go to First Page"
            onPress={() => navigation.navigate('FirstPage')}
          />
          <Button
            title="Go to Third Page"
            onPress={() =>
              navigation.navigate(
                'ThirdPage', { someParam: 'Param1' }
              )
            }
          />
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey'
          }}>
          Navigate Between Screens using
          {'\n'}
          React Navigation
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey'
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
}

export default SecondPage;

pages/ThirdPage.js

Open ThirdPage.js in any code editor and replace the code with the following code.

// Navigate Between Screens using React Navigation in React Native //
// https://aboutreact.com/react-native-stack-navigation //
import * as React from 'react';
import { Button, View, Text, SafeAreaView } from 'react-native';

const ThirdPage = ({ route, 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 Third Page of the App
            {'\n'}
            {route.params.someParam}
          </Text>
          { route.params.someParam != 'reset' ?
            <Button
              title="Go back"
              onPress={() => navigation.goBack()}
            />
            :null
          }
          <Button
            onPress={() => navigation.navigate('SecondPage')}
            title="Go to Second Page"
          />
          <Button
            title="Reset navigator to First Page"
            onPress={() =>
              navigation.reset({
                index: 0,
                routes: [
                  {
                    name: 'FirstPage',
                    params: { someParam: 'reset' },
                  },
                ],
              })
            }
          />
        </View>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey'
          }}>
          Navigate Between Screens using{'\n'}React Navigation
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey'
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
}

export default ThirdPage;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

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

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

StackNavigationExample1   StackNavigationExample2   StackNavigationExample3   StackNavigationExample4   StackNavigationExample5

Output in Online Emulator

This is how you can navigate between screens using React Navigation 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!

I hope you liked it. 🙂

3 thoughts on “Navigate Between Screens using React Navigation V6 in React Native”

Leave a Comment

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