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

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

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