How to Use Routing with React Navigation in React Native ?
Almost every mobile application requires navigating between different screens. React Native provides an elegant and easy-to-use library to add navigation to native applications: react-navigation. It is one of the most popular libraries used for routing and navigating in a React Native application.
Transitioning between multiple screens is managed by Navigators. React Navigation allows various kinds of navigators, like Stack Navigators, Drawer Navigators, Tab Navigators, etc. Along with navigating between multiple screens, it can also be used for sharing data between them.
Approach: We will be using the StackNavigator provided by React Navigation. It is used to allow transitions between screens wherein every new screen is placed on top of a stack. In our example, we will be creating 3 screens and transitioning between them using the StackNavigator. We will also learn how to pass data from one screen to another and display it in the screen header along with basic transitioning.
Creating application and installing modules:
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.
expo init react-navigation-routing
Step 3: Now go into your project folder i.e. react-navigation-routing
Step 4: Install the required packages using the following command:
npm install –save react-navigation react-navigation-stack react-native-reanimated react-native-gesture-handler react-native-screens react-native-vector-icons
Project Structure: The project directory should look like the following:
Example: In this example, we will create 3 screens, namely, Home Screen, Profile Screen, and Settings Screen. We will use a Stack Navigator and configure it with some basic styles. We will also dynamically send data from one screen and display it as the header title on another screen (take input from the user on the Home Screen, pass it on to the Profile Screen, and display it on the Header of the Profile Screen.
This file contains the basic Navigator setup. We will use the createStackNavigator() method provided by the react-navigation-stack library to create our stack navigator. Some basic styles are provided to all the 3 screens using the default navigation options.
This is the first screen of our stack. In this screen, we will ask the user to provide a profile name as an input which we will pass to the “Profile” screen.
This screen will receive the input given by the user in the Home Screen using the navData object and display it in its header.
This is a simple screen with a button to go back to the Home Screen.
Step to run the application: Start the server by using the following command.