Skip to main content

React Native Navigation

React Native Navigation is used for managing the presentation, and transition between multiple screens. There are two types of navigation built in mobile applications. These are stack navigation and tabbed navigation patterns.

React Navigation Installation

React Navigation is generated from React Native community that provides the navigation solution written in JavaScript.
Create the React Native project and install the required packages and dependencies.

Install the react-navigation package in React Native project using any one of the below command.

  1. yarn add react-navigation  
  2. # or with npm  
  3. # npm install --save react-navigation  

After successful execution of the above command, it adds the "react-navigation": "^3.3.0" (3.3.0 is version) in package.json file.
After that, install react-native-gesture-handler package.

  1. yarn add react-native-gesture-handler  
  2. # or with npm  
  3. # npm install --save react-native-gesture-handler  

Now, link all the native dependencies together using command:

  1. react-native link react-native-gesture-handler  

To complete the installation of 'react-native-gesture-handler' for Android, make the following modification in MainActivity.java.
projectDirectory/android/app/src/main/java/com/project/MainActivity.java

  1. import com.facebook.react.ReactActivityDelegate;  
  2. import com.facebook.react.ReactRootView;  
  3. import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;  
  4.   
  5. . . .  
  6.   
  7. @Override  
  8. protected ReactActivityDelegate createReactActivityDelegate() {  
  9.     return new ReactActivityDelegate(this, getMainComponentName()) {  
  10.         @Override  
  11.         protected ReactRootView createRootView() {  
  12.             return new RNGestureHandlerEnabledRootView(MainActivity.this);  
  13.         }  
  14.     };  
  15. }  

Creating a stack navigator

To create a stack navigation, we import createStackNavigator and createAppContainer functions of react-navigation library.

App.js

  1. import React from "react";  
  2. import {Button, View, Text } from "react-native";  
  3. import { createStackNavigator, createAppContainer } from "react-navigation";  
  4.   
  5. class HomeScreen extends React.Component {  
  6.     render() {  
  7.         return (  
  8.             <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>  
  9.                 <Text>Home Screen</Text>  
  10.             </View>  
  11.         );  
  12.     }  
  13. }  
  14.   
  15. const AppNavigator = createStackNavigator({  
  16.     Home: {  
  17.         screen: HomeScreen  
  18.     }  
  19. });  
  20. export default createAppContainer(AppNavigator);  

The createStackNavigator is a function which takes a route configuration object and options object. It returns the React component.

MainActivity.java

  1. package com.naviexe;  
  2.   
  3. import com.facebook.react.ReactActivity;  
  4. import com.facebook.react.ReactActivityDelegate;  
  5. import com.facebook.react.ReactRootView;  
  6. import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;  
  7.   
  8. public class MainActivity extends ReactActivity {  
  9.   
  10.     @Override  
  11.     protected String getMainComponentName() {  
  12.         return "naviExe";  
  13.     }  
  14.     @Override  
  15.     protected ReactActivityDelegate createReactActivityDelegate() {  
  16.         return new ReactActivityDelegate(this, getMainComponentName()) {  
  17.             @Override  
  18.             protected ReactRootView createRootView() {  
  19.                 return new RNGestureHandlerEnabledRootView(MainActivity.this);  
  20.             }  
  21.         };  
  22.     }  
  23. }  

When we run the above code, we see an empty navigation bar containing the HomeScreen component.

Output:

React Native Navigation

Shorthand route configuration

When we have only a single screen as route that is Home screen component, we do not need to use the {screen: HomeScreen} , we can directly use the home component.

  1. const AppNavigator = createStackNavigator({  
  2.     Home: HomeScreen  
  3. });  

Adding title and styling navigation

  1. static navigationOptions = {  
  2.     title: 'Home',  
  3.     headerStyle: {  
  4.         backgroundColor: '#f4511e',  
  5.     },  
  6.     headerTintColor: '#0ff',  
  7.     headerTitleStyle: {  
  8.        fontWeight: 'bold',  
  9.     },  
  10. };  
  1. import React from 'react';  
  2. import { View, Text } from 'react-native';  
  3. import { createStackNavigator, createAppContainer } from 'react-navigation';  
  4.   
  5. class HomeScreen extends React.Component {  
  6.     static navigationOptions = {  
  7.         title: 'Home',  
  8.         headerStyle: {  
  9.             backgroundColor: '#f4511e',  
  10.         },  
  11.       //  headerTintColor: '#0ff',  
  12.         headerTitleStyle: {  
  13.            fontWeight: 'bold',  
  14.         },  
  15.     };  
  16.     render() {  
  17.         return (  
  18.             <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>  
  19.                 <Text>Home Screen</Text>  
  20.             </View>  
  21.         );  
  22.     }  
  23. }  
  24. const AppNavigator = createStackNavigator({  
  25.     Home: HomeScreen  
  26. });  
  27.   
  28. export default createAppContainer(AppNavigator);  

Adding a second route screen

Create another class (ProfileScreen) in App.js file to add the second route screen to the stack navigator.

  1. class ProfileScreen extends React.Component {  
  2.     render() {  
  3.         return (  
  4.             <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>  
  5.                 <Text>Details Screen</Text>  
  6.             </View>  
  7.         );  
  8.     }  
  9. }  
  10.   
  11. const AppNavigator = createStackNavigator(  
  12.     {  
  13.         Home: HomeScreen,  
  14.         Profile: ProfileScreen  
  15.     },  
  16.     {  
  17.         initialRouteName: "Home"  
  18.     }  
  19. );  

The initialRouteName options object specifies the initial route in the stack navigation.

Complete code:

App.js

  1. import React from 'react';  
  2. import { View, Text } from 'react-native';  
  3. import { createStackNavigator, createAppContainer } from 'react-navigation';  
  4.   
  5. class HomeScreen extends React.Component {  
  6.     render() {  
  7.         return (  
  8.             <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>  
  9.                 <Text>Home Screen</Text>  
  10.             </View>  
  11.         );  
  12.     }  
  13. }  
  14. class ProfileScreen extends React.Component {  
  15.     render() {  
  16.         return (  
  17.             <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>  
  18.                 <Text>Details Screen</Text>  
  19.             </View>  
  20.         );  
  21.     }  
  22. }  
  23.   
  24. const AppNavigator = createStackNavigator(  
  25.     {  
  26.         Home: HomeScreen,  
  27.         Profile: ProfileScreen  
  28.     },  
  29.     {  
  30.         initialRouteName: "Home"  
  31.     }  
  32. );  
  33.   
  34. export default createAppContainer(AppNavigator);  

Output:

React Native Navigation

In the next section, we will learn how to go from Home route to Profile route (one screen to another).

Comments

Popular Posts

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...