How to navigate between screens in a react native application
Blog

How to navigate between screens in a React Native application

Navigation is very important in any kind of application e.g. in Whatsapp we have to switch between different screens frequently, like coming back to the Chats screen from the settings screen or checking Status screen from Calls list screen. In this blog post I would explain how can we add navigation system between screens using the React navigation library.

For demonstration purpose we will build two screens, HomeScreen and AboutScreen. We’ll add this button to navigate between these two screens.

Prerequisites -

Step 1:

(a) At first, Create a new React Native app using below steps

  • In your terminal change the path to the directory/folder where you want to create your project.
  • Run command :

    npx react-native init my_first_rn_app
            command to create new project in react native

After installation, the terminal of the newly created React-native app will look like the image shown below.

This screenshot shows the status when project has been created

Step 2:

Open project in VS code (Or in any editor) and then open terminal.

(a) At first Install @react-navigation/native

npm install @react-navigation/native

(b) Install @react-navigation/stack

npm install @react-navigation/stack

(c) Now Install all the peer dependencies one by one

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

Step 3:

Open the App.js file and replace your code by the below code:

Step 4:

(a) Create Home screen

  • Create a HomeScreen.js file and place the below code in this file

(b) Create About Screen

  • Create AboutScreen.js file and add the below code in this file

Step 5:

Running our app
Command:

npx react-native run-android

After running your app, the screen below will appear.
This screenshot shows the home screen

Now Click on the ABOUT PAGE button and the screen shown below may appear.

This screenshot shows the about screen

You can click on BACK TO HOME to navigate on the home screen or by clicking on the back icon at the left top.

Conclusion:

We built an app with two screens i.e home and about. We have used the React navigation library. We learnt about this.props.navigation which is used to inherit props from the navigation object. There are more ways like i.e. React Native Router Flux, React Router Native, etc to achieve routing in react native. I will be covering these in future articles. Stay tuned.

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch