Saturday, October 27, 2018

Navigating Between Screens or Activities Using React Navigation Library - Android

This tutorial explains how to move or navigate from one screen to another using React Navigation Library in react native application. In a web browser, you can link to different pages using an anchor (<a>) tag. When the user clicks on a link, the URL is pushed to the browser history stack. When the user presses the back button, the browser pops the item from the top of the history stack.
Similarly, React Navigation's stack navigator provides a way for your app to transition between screens and manage navigation history.React Navigation is that React Navigation's stack navigator provides the gestures and animations that you would expect on Android and iOS when navigating between routes in the stack.

react-navigation version : 2.6.2

Before we start the tutorial, we need to aware of some important function, which we required during the page navigation from one screen to another. So Lets get started :
  1. createStackNavigator  : createStackNavigator is a function that takes a route configuration object and an options object and returns a React component. Basically here we are maintaining the route information for different screen or activity.
  2. navigation prop : The navigation prop is available to all screen components, that helps for screen navigation.
  3. this.props.navigation.navigate('RouteName')pushes a new route to the stack navigator if it's not already in the stack, otherwise it jumps to that screen and pops the already open screen.
  4. this.props.navigation.push('RouteName') : pushes a new route to the stack navigator even if already present in the stack.
  5. this.props.navigation.goBack() : when you switch to new window using stack navigator, then it will automatically enabled the back button in header bar.(On Android, the hardware back button just works as expected.) Also you can do the same programmatically by calling the goBack() function.
  6. this.props.navigation.popToTop() : This function helps to switch back to the home or first screen of your react native application.
Navigating Between Screens or Activities Using React Navigation Library - Android
In this example, we will create simple navigation example, where we move from one activity or screen to another on click button.

React Native Navigation Between Screen on Button Click :

Project Structure :
Lets see the project structure.

Navigating Between Screens or Activities Using React Navigation Library - Android


Lets follow the below steps, this will helps to navigate from one activity to another in react native application.



Step-1 :  Install the react-navigation package in your React Native project. Refer the below screenshot, while installing react navigation package.
Command :
npm install --save react-navigation



Once installation complete check you package.json file in react native application. You  will find  react-navigation installed version in dependencies section.
{
  "name": "MobileApp56",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.3.1",
    "react-native": "0.55.4",
    "react-navigation": "^2.6.2"
  },
  "devDependencies": {
    "babel-jest": "23.2.0",
    "babel-preset-react-native": "4.0.0",
    "jest": "23.3.0",
    "react-test-renderer": "16.3.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

Step-2 Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step-3: Lets create a new component named as HomeActivity. This component will be the home screen or default screen.  when user launch this application, then react native render home screen first.
  • Add static navigationoptions object inside the class. A HomeActivity component consists of a static property called navigationOptions which is an object that returns an object that contains various configuration options. Using the static navigationoptions  we can set our activity title name, color and font weight.
  • Implement render method and return Text and Button component wrapped by root View component. When user clicks on Button, it will navigate the screen from HomeActivity to ProfileActivity.
  1. When user clicks on "Go to Profile Activity" Button, then will navigate the user to profile screen.
complete source code for HomeActivity.js file.

HomeActivity 
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Button
} from 'react-native';

class HomeActivity extends React.Component {
 
   static navigationOptions = {
    title: 'Home',
 headerStyle: {
      backgroundColor: '#03A9F4',
    },
 headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
 
  }; 
 
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.headerText} >Home Activity</Text>
        <Button
          title="Go to Profile Activity"
          onPress={() => this.props.navigation.navigate('Profile')}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  headerText: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
 fontWeight: 'bold'
  },
  
});

export default HomeActivity;

Step-4: Lets create a new component named as ProfileActivityThis component will be the second screen. when clicks on "Go to Profile Activity" button in HomeActivity screen, then it will display the profile screen.
  • Add static navigationoptions object inside the class. A HomeActivity component consists of a static property called navigationOptions which is an object that returns an object that contains various configuration options. Using the static navigationoptions  we can set our activity title name, color and font weight.
  • Implement render method and return Text and Button component wrapped by root View component. 
  1. When user clicks on "Go to Home Activity" Button, then will navigate the user to home screen back.
  2. When user clicks on "Go to new Profile Activity" Button, then will create new profile screen in stack navigator.
  3. When user clicks on "Go Back" Button, then will navigate the screen to home screen.

complete source code for ProfileActivity.js file.

ProfileActivity 
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, { Component } from "react";
import { Platform, StyleSheet, Text, View, Button } from "react-native";

class ProfileActivity extends React.Component {
  static navigationOptions = {
    title: "Profile",
    headerStyle: {
      backgroundColor: "#E91E63"
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.headerText}>Profile Activity</Text>
        <Button
          title="Go to Home Activity"
          onPress={() => this.props.navigation.navigate("Home")}
        />

        <Text style={styles.headerText}>create new profile screen </Text>
        <Button
          title="Go to new Profile Activity"
          onPress={() => this.props.navigation.push("Profile")}
        />

        <Text style={styles.headerText}> Go Back </Text>
        <Button
          title="Go Back"
          onPress={() => this.props.navigation.goBack()}
        />

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  headerText: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    fontWeight: "bold"
  }
});

export default ProfileActivity;

Step-5: Open index.android.js  / index.ios.js  in your favourite code editor and erase all code and follow this tutorial.

Step-6: Through react react-native  packages import all required components. Also perform below imports :
  • Included additional import from react-navigation package.
  • Included custom component import from HomeActivity and ProfileActivity js file.
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, YellowBox } from 'react-native';
import { createStackNavigator } from 'react-navigation';
import HomeActivity from './component/activity/HomeActivity';
import ProfileActivity from './component/activity/ProfileActivity';

Step-7: Add <RootStack /> component inside the app.js file and all the route configuration is specified in the options parameter to the createStackNavigator function. For example : In createStackNavigator function we are setting the route configuration as Home for HomeActivity Component.
const RootStack = createStackNavigator(
{
  Home: { screen: HomeActivity },
  Profile: { screen: ProfileActivity },
},
{
    initialRouteName: 'Home',
}

);

Step-8 : As you know In React Native, the component exported from App.js is the entry point (or root component) for react app and in order to get complete access or control over the RootStack component, we need to wrapped by root View component inside the render block.
So let's export a component that just renders our RootStack stack navigator.
export default class App extends Component {
  render() {
    return <RootStack />;
  }
}

Step-9 : During the design phase, you may have seen yellow color warning box  just below the main screen. Lets use the below line of code, it will hide the warning message in your application. For that you need ignoreWarnings function and specify the warning message parameters that you want to hide. In our case we getting below messages.
YellowBox.ignoreWarnings(
      ['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader'
]);

Complete Source Code for App.js 

Lets see the complete source code that helps to Navigating Between Screens or Activities Using React Navigation Library in react native application.
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, YellowBox } from 'react-native';
import { createStackNavigator } from 'react-navigation';
import HomeActivity from './component/activity/HomeActivity';
import ProfileActivity from './component/activity/ProfileActivity';

const RootStack = createStackNavigator(
{
  Home: { screen: HomeActivity },
  Profile: { screen: ProfileActivity },
},
{
    initialRouteName: 'Home',
}

);

export default class App extends Component {
  render() {
    return <RootStack />;
  }
}

YellowBox.ignoreWarnings(
      ['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader'
]);

Screenshot :

Navigating Between Screens or Activities Using React Navigation Library - Android


Navigating Between Screens or Activities Using React Navigation Library - Android



This is all about Navigating Between Screens or Activities Using React Navigation Library in react native application.Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

Download Link : 
https://github.com/skptricks/React-Native/tree/master/Navigating%20Between%20Screens%20or%20Activities%20Using%20React%20Navigation%20Library%20-%20Android


5 comments:

  1. how to implement react navigation for ios
    can you please suggest me because i am trying it since last three days but did not getting any result

    ReplyDelete
    Replies
    1. If you're using React Navigation within a hybrid app - an iOS app that has both Swift/ObjC and React Native parts - you may be missing the RCTLinkingIOS subspec in your Podfile, which is installed by default in new RN projects. To add this, ensure your Podfile looks like the following:

      pod 'React', :path => '../node_modules/react-native', :subspecs => [
      . . . // other subspecs
      'RCTLinkingIOS',
      . . .
      ]

      Delete
  2. Running application "screen" with appParams: {"rootTag":21}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF


    After Running my application the above mentioned error is appear
    can you please me..

    ReplyDelete
  3. All time display "the development server returned 500 react native" , and when we try to change react native version same as your code then again display same error..
    What I can do?

    ReplyDelete
    Replies
    1. Which version of react native application are you using now ?

      Delete