Routing with React Navigation in React Native

Author - Nishita
React Navigation

Almost for all mobile application’s user experience play a great role in its success, the transition between multiple screens and tabs become a vital part for application’s user experience. In this article, you will learn about various navigation components available in React Native, how to implement React Navigation and react-routing for your React Native application.

Hence with the help of React Navigation, we will implement any complex screen flow very easily for your application. As a result in this article, I have used the common scenario of navigation which is required for most of the application e.g. Login/SignUp flow and tab bar after successful login.

Here first you will learn about React Navigation in detail and then you will learn Routing. Before starting with Stack navigation let’s take a small overview of react-navigation.

React Navigation

React Navigation is a very much popular JavaScript-based library for routing and navigation in a React Native app. Having official support from both Facebook and React Native documentation for routing support.

Getting started with React Navigation

Before starting implementation of React Navigation let’s learn basic terms used.

1. Header

Also known as navigation header, navigation bar, navbar, and probably many other things. This is the rectangle at the top of your screen that contains the back button and the title for your screen. The entire rectangle is often referred to as the header in React Navigation.

2. Screen Component

A screen component is a component that we use in our route configuration.

const AppNavigator = createStackNavigator(
  {
    Home: {
      screen: HomeScreen,    // <----
    },
    Details: {
      screen: DetailsScreen, // <----
    },
  },
  {
    initialRouteName: 'Home',
  }
);

3. Navigation Prop

This prop will be passed into all screens, and it can be used for the following

> dispatch will send an action up to the router

> state is the current route for the screen

> getParam is a helper to access a param that may be on the route

> navigate, goBack, etc are available to dispatch actions in a convenient way

Navigators can also accept a navigation prop, which they should get from the parent navigator, if there is one.

4. Navigation State

The state of a navigator generally looks something like this:

{

  key: 'StackRouterRoot',

  index: 1,

  routes: [

    { key: 'A', routeName: 'Home' },

    { key: 'B', routeName: 'Profile' },

  ]

}

For this navigation state, there are two routes (which may be tabs, or cards in a stack). The index indicates the active route, which is “B”.

5. Route

Each route is a piece of navigation state which contains a key to identify it, and a “routeName” to designate the type of route. It can also contain arbitrary params:

{        
     key: ‘B’,
     routeName: ‘Profile’,
     params: { id: ‘123’ }
}

6.  Child Navigation State

When composing navigators, it is possible for a route to be a navigation state. It would look like this:

When composing navigators, it is possible for a route to be a navigation state. It would look like this:

{

  key: 'B',

  routeName: 'Profile',

  params: { id: '123' },

  index: 1,

  routes: [ {...}, {...} ]

}

StackNavigator with React Navigation

React navigation’s stackNavigator provides a way for your app to navigate between screens and manage navigation history. Each screen we navigate to is pushed to the top of the stack, and each time we hit the back button, this screen pops off the top of the stack.

Before moving forward lets learn these basic terms for stack Navigation.

> initialRouteName : Set default screen of stack.

> initialRouteParams : Set params for initials route.

> initalRouteKey : Optional identifier of the initial route.

> defaultNavigationOptions : Default navigation options to use for screens.

> paths : Mapping of overrides for the paths set in route config.

Create a new project and set up stack navigation using ‘react-navigation’.

react-native init ReactRouting
cd ReactRouting
npm install

Install react-navigation to your project

npm install —save react-navigation

Next, create a file called LoginRouter.js file and write below code:

import { createStackNavigator, createAppContainer } from "react-navigation";

import Signup from "../Login/Signup";
import Login from "../Login/Login";

const AppNavigator = createStackNavigator(
    {
        Login: {
            screen: Login,
        },
        Signup: {
            screen: Signup,
        },
    },
    {
        initialRouteName: 'Login',
        headerMode: "none",
        navigationOptions: {
            header: null,
        },
    },
);
export default createAppContainer(AppNavigator);

Maybe this is very basic stack flow with two screen for Login and Signup. You can navigation between login and signup screen using below code.

<TouchableOpacity onPress={() => this.props.navigation.navigate('Signup')}>

TabNavigator with React Navigation

React navigation’s tabNavigator provides a way for your app to switches between screens or transition between routers. Possibly the most common style of navigation in mobile apps is tab-based navigation. This can be tabs on the bottom of the screen or on the top below the header.

Here is sample code for tab navigation using react-navigation.

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { createBottomTabNavigator, createAppContainer } from "react-navigation";

import Firstscreen from '../TabScreens/Firstscreen';
import Secondscreen from '../TabScreens/Secondscreen';
import Thirdscreen from '../TabScreens/Thirdscreen';
import Fourthscreen from '../TabScreens/Fourthscreen';

const mainTab = createBottomTabNavigator(
    {
        Firstscreen: Firstscreen,
        Secondscreen: Secondscreen,
        Thirdscreen: Thirdscreen,
        Fourthscreen: Fourthscreen,
    },
    {
        tabBarPosition: "bottom",
        animationEnabled: false,
        tabBarOptions: {
            activeTintColor: 'rgb(125,107,255)',
            indicatorStyle: {
                backgroundColor: "#A1A1A1",
                height: 1,
            },
            labelStyle: {
                fontSize: 8,
                color: "#A1A1A1",
            },
            style: {
                backgroundColor: 'rgb(255,255,255)',
            },
            scrollEnabled: false,
            showLabel: false,
            showIcon: true,
        },
    }
);

export default createAppContainer(mainTab)

Tab Appearance

Here you can customise appearance using below props as shown in code.

static navigationOptions = {
        tabBarLabel: "First",
        header: false,
        tabBarIcon: ({ tintColor }) => (
            <Image
                source={require("../Resources/home.png")}
                style={[{ tintColor: tintColor, width: 18, height: 18 }]}
            />
        ),
 };

Switching from one tab to another has a familiar API

this.props.navigation.navigate

Final Thoughts

Finally, you have learned React Navigation with different kind of routing options that will help you to build your new apps. If you are stuck on any part of this article, you can see the final version of code on GitHub. Waiting for your comments below!

Free SEO Checker |
Test your website for free with OnAirSEO.com

Get Your SEO report!

Don’t miss the next post!

Loading

Related Posts