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

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

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...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...