Codementor Events

React-native react-navigation tutorial v5x

Published Jul 11, 2020
React-native react-navigation tutorial v5x

React-native navigation is a library that helps you to create and navigate through multiple screens in your react-native project with ease. When building a mobile application with react-native you most likely would want to build a cross-platform application which means you plan to support both Android and IOS devices, using react-navigation helps you save time in implementing and optimizing navigation code for each of these platforms.

React-native navigation provides you with all transitions and animations that’ll give your mobile application that Native and modern feeling, it comes with some features like Tab navigation, Stack Navigation, Drawer Navigation.

This article will help you with getting started with react-navigation and also talk about working with navigators.

Dependecies To Install
To get started with react-navigation, you must install it into your project using npm or yarn:

npm install @react-navigation/native
  Or 
    yarn add @react-navigation/native

You’ll also need to install some other utilities that navigators would use to create the navigation structure in your application, you’ll need to install these dependencies into your expo project using expo in the command line, in your project directory run the following command:

expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view

react-native-gesture-handler: React Native Gesture Handler provides native-driven gesture management Apis for building best touch-based experiences in React Native.

react-native-reanimated: React Native Reanimated provides a more comprehensive, low level abstraction for the Animated library Api to be built on top of and hence allows more flexibility mostly in gesture based interactions.

react-native-screens: React Native Reanimated provides native primitives to represent screens instead of plain View components in order to take advantage of the operating system behaviour and optimizations around screens.

react-native-safe-area-context: React Native Safe Area Context provides a flexible Api for accessing a device safe area inset information. This allows you to position appropriately around status bar home indicators and other devices and OS interface elements.

@react-native-community/masked-view: React Native Community/masked View provides a masked view which only displays the pixels that overlap with the view rendered in its mask element.

Now you can go ahead and make some imports in your project, first, you must import Navigation Container from react-navigation/native, as seen below:

Import { NavigationContainer } from ‘@react-navigation/native’

Before going into how to implement react-navigation in your project, you need to know the importance of navigators and how essential they are in react-navigation.

Working With Navigators
If you’re familiar with web development, you’ll know that you can navigate between pages using the anchor tag ('< a >'), the navigator is very similar to that. When implementing react-native navigation in your react-native project you must work with several navigators that will be linked and their relationship would state the flow and the organization of your application. React-native navigation has various types of navigators like Stack Navigator, Tab Navigator, Drawer Navigation, but we’ll only be talking about the Stack-navigator in this article because it’s the navigator that is needed to move between screens in our application. Stack-navigator gives us the ability to transition between screens in our application and also manage our navigation history. React-native navigation’s stack-navigator uses the push (this add items to the end of an array) and pop (this removes an item from the end of an array) methods to add and remove items from the navigation stack which is very similar to that of a web browser, the only difference is that stack-navigator comes with gestures and animations that you would see on the mobile device (IOS, Android) when navigating between screens.

Note: A screen in react native is just a react component that displays on a mobile device because of its render function, which is anything that we can see in a react native application.

Navigating Using The Stack Navigator
To use Stack navigator in your project you’ll need to import createStackNavigator this will require you to install the Stack navigator library. We must install react-navigation/stack with either npm or yarn as seen below:

npm install @react-navigation/stack
  Or 
yarn add @react-navigation/stack

We’ll then import createStackNavigator from react-navigation/stack as seen below:

Import { createStackNavigator } from ‘@react-navigation/stack’;

Now our root file should look similar to this;

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

Then we use stack navigator by calling the createStackNavigator and assigning it to a constant as seen below:

const Stack = createStackNavigator();

We then create our navigation stack as a react element, we would use stack with Screen and Navigator they are both react elements and object gotten from createStackNavigator. The Screen element should be nested inside of the Navigator element which would be like a parent and child relationship. The NavigationContainer holds the navigation state and it also controls the navigation tree. The NavigationContainer acts like a container, which means we’d wrap our navigation structure with this component. You can look at the example below to understand better:

const Stack = createStackNavigator();
 
ExampleNavigation = () => {
  return (
 <NavigationContainer>
    <Stack.Navigator initialRouteName="exampleOne">
      <Stack.Screen
        name="exampleOne"
        component={exampleOneScreen}
        options={{ headerTitle: ‘exampleOneHeader’ }}
      />
      <Stack.Screen
        name=”exampleTwo”
        component={exampleTwoScreen}
        options={{ headerTitle: ‘exampleTwoHeader’ }}
      />
      <Stack.Screen
        name="exampleThree"
        component={exampleThreeScreen}
        options={{ headerTitle: ‘exampleThreeHeader’ }}
      />
      </Stack.Navigator>
  </NavigationContainer>
  );
};

As you can see in the example above, the Navigation Container wraps all the other components, then we have the Stack Navigator which contains the screen elements as its children to define the configuration routes. The Stack Screen represents a component that renders content to the screen of the device inside the screen element we have three props which are the name (the name of the screen, you could also see this as the id of the screen), the component (this is the component that you intend to render it doesn’t matter if it's a class-based component or a function you just need to pass in the component's name) and the options prop, this is used to add other customizations to your screen like a heder title or a header button, etc. The example above clearly states that the project has three screens and we can also see a prop passed into the Stack Navigator showing the initial route which we can also call the home screen “exampleOne”, and if we want to move between screen all we need to do is to set up a call back function inside the active component that would navigate to our desired component, we’d do this by passing a navigation prop inside the call back function of the active component, you can see the example below to understand how to implement this:

Import React from ‘react’;
Import {View, Text, Button} from ‘react-native’
 
const exampleOneScreen = ({navigation}) => {
  return (
      <View>
        <View>
          <Text>
            This is the exampleOne screen, and this is 
            also the home screen of this project
          </Text>
        </View>
  <Button 
          title=”switchScreen”
          onPress={()=>
          navigation.navigate(‘exampleTwo’)}
        />
    </View>
  );
}

As you can see from the example above we use the navigation prop in a callback function to navigate to the screen of our choice using the name of the screen as an id. We would then use ExampleNavigation as a react element to the root of our application, which means this is the component that renders when our application starts up.

Discover and read more posts from Nwoga kingsley
get started