Aage ki Socho

HomeBlogWeb DevelopmentReact Navigation Implementation Guide with Examples

React Navigation Implementation Guide with Examples

Published
13th Oct, 2023
Views
view count loader
Read it in
10 Mins
In this article
    React Navigation Implementation Guide with Examples

    React Navigation offers ideal steering and routing on both Android and iOS for React Native applications. Understanding the React Native fundamentals will help you strengthen your knowledge in React and front-end web development endeavors. Furthermore, you can add the React Navigation properties to your applications through navigation, much of which will be discussed here sequentially.

    In this tutorial, we will walk you through the basics of React Navigation and cover the most common navigation to strengthen your web development skills. Furthermore, we will discuss how to start using React Navigation in a React Native app and guide you through some React Native Navigation examples. Avid developers like you can pick React Native certification courses and hone your expertise in App development.

    What is React Navigation?

    React Navigation is a standalone library that allows you to route, navigate and execute the navigation function in a React Native app. It comprises a chain of navigators useful for defining the screen flow of an application.

    React Navigation is coded in JavaScript and doesn’t use a single native navigation API on Android and iOS directly. Instead, it reconstructs some subsections of those APIs. This permits all-out customization, simpler debugging, and integration of third-party JS plugins, with no requirement of learning Kotlin, Java, Swift, Objective-C, or any other programming language.

    What is React Native Navigation?

    React Native Navigation is a common substitute to React Navigation. It is a unit reliant on and developed for use with React Native. As it uses Native Navigation APIs on Android and iOS directly, using React Native Navigation enables a more natural feel and look.

    React Native Navigation is used to manage presentations and transition between screens. Generally, stack navigation and tabbed navigation patterns are the two categories of navigation built-in mobile applications.

    What’s New in React Navigation 6.0 

    Currently, the most stable release of React Navigation is 6.0, which is being used at the time of writing this tutorial. If you are using version 5.0 or any older version, consider updating to the most updated version by visiting React Navigation official site to leverage the core React Navigation library and advanced functionalities.

    Let us check out the key changes and newly added features included in React Navigation 6.0:

    1. Verses React Navigation 5.0, where only the params merging option was available, the new release allows merging and overwriting.
    2. For iOS, modals in stack presentation style are by default, whereas there is a new slide animation for modals on Android.
    3. A new component called Group has been included for grouping screens.
    4. The tabBarOptions and drawerContentOptions have been replaced with the prop on the screen, which makes it possible to configure the screens individually.
    5. By default, the drawers use slide animation on iOS.
    6. Version 6.0 uses the Material Top Tabs as a ViewPager based implementation that facilitates a native experience.

    APIs in React Native Navigation and React Navigation 

    React Navigation contains an indicative API with in-built react hooks. On the other hand, React Native Navigation contains an imperative API with a communal library for Hooks.

    React has altered how developers think regarding interface development. Today, devs search for a more declarative API rather than an imperative one. React Hooks add a bit more ice on top of the concept. Between React Native Navigation and React Navigation, the former offers APIs that are closer to a React component API, more declarative, and simpler to implement for React devs. While RNN depends on imperative APIs, that may be necessary for the architecture. Regarding Hooks, RNN contains a community library, while React Navigation contains in-built Hooks.

    Performance in React Native Navigation and React Navigation

    React Navigation contains a blend of libraries to offer a near-native experience, while RNN employs natural fragments for every screen.

    Functionality is the first parameter when choosing a steering library for your application. The figure of frames shown per second regulates the evenness of the display. Most efficient applications usually uphold 60fps, particularly during transitions and interactions.

    Equated to React Navigation, React Native Navigation, by default sets all of a user’s screens as single React apps, which makes the application more efficient by nature. However, it comes with a bit of complication, specifically when mixing with libraries like react-intl and Redux that need to be wrapped into the app. You will later learn about the integration comparison.

    Installing React Navigation

    If you have not already installed the react-navigation package, then the first step is to install the package and its dependencies. Run the following expo install command together to install React in your system:

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

    Alternatively, you can also use install React using the yarn package manager:

    yarn add @react-navigation/native

    Setup of React Navigation

    Firstly, we are going to begin by using a React stack navigator. A React Navigation modal pops and pushes and routes and does the same to and from a stack.

    A stack navigator is a stack that contains your applications’ routes. By default, your first screen is considered the root screen. As you shift through the application’s screens, the new screen is set on the stack’s top. To begin with React Navigation, you will have to distinctly install the react-navigation-stack package:

    npm install --save react-navigation-stack

    Now you are ready to amend the App.js/App.tsx file so as to use the React stack navigator:

    import { StatusBar } from 'expo-status-bar';
    import React from 'react';
    import { View, Text, StyleSheet, Button } from 'react-native';
    import { NavigationContainer } from '@react-navigation/native';
    import { createStackNavigator } from '@react-navigation/stack';
    import { HomeScreen } from './HomeScreen';
    import { DetailsScreen } from './DetailsScreen';
    import { ContactScreen } from './ContractScreen';
    const Stack = createStackNavigator();
    export default function App() {
      return (
        <NavigationContainer>
          <Stack.Navigator>
            <Stack.Screen
              name="Home"
              component={HomeScreen}
              options={{ title: 'My Home Screen' }} />
           
            <Stack.Screen
              name="Details"
              component={DetailsScreen}  />
           
             <Stack.Screen
              name="Contact"
              component={ContactScreen}  />
           
          </Stack.Navigator>
        </NavigationContainer>
      );
    }
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      },
    });

    Keynotes on the above:

    • First, you import all your screens, as is usually done in any React Native app.
    • Then, initiate your stack using createStackNavigator and create a stack screen for each of your application’s screens using the components.
    • Finally, you will wrap your stack screens with NavigationContainer, which is accountable for handling your application’s state.

    React Native Stack Navigator

    React Navigation is designed using JavaScript and enables you to develop navigation patterns and components that feel and appear like accurate native ones. It uses react native stack navigator to handle the presentation and steering history of the proper screen according to the route taken by the user inside the application. Only a single screen is shown to the user at a particular time.

    Visualize a stack of books; navigating to a new screen puts it on top of the stack, and navigating back eliminates it from the stack. Additionally, the stack navigator offers gestures and transitions that feel like those of native Android and iOS. You should also know that an application can contain more than a single stack navigator.

    If you want to become a mobile app developer, check out mobile app development today to get started.

    Usage of React Native Navigation 

    Let us explore further and have a look at the usage of React Native Navigation:

    1. Homescreen.tsx
    import React from 'react';
    import { View, Button, Text, StyleSheet } from 'react-native';
    export function HomeScreen(props: any) {
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text style={{ fontSize: 20 }}>Home Screen</Text>
                <Button
                    title="Go to Details"
                    onPress={() => {
                        props.navigation.navigate('Details', {
                            userId: 1,
                            userName: 'Awesome User',
                        });
                    }
                    }
                />
            </View>
        );
    }

    Keynotes on the above:

    • Every screen packed with the stack will carry navigation as props. Thus, all screens will have access to the Navigation navigate() function.
    • In the navigate() function, the first parameter represents the name of the screen which is set in App.tsx, whereas the first parameter represents any details we pass between screens. Unlike the first mandatory parameter, the second one is optional. In this guide, we are passing a user ID and name as parameters.

    2. DetailsScreen.tsx

    import React from 'react';
    import { View, Button, Text, StyleSheet } from 'react-native';
    export function DetailsScreen({ route, navigation }: any) {
        const { userId } = route.params;
        const { userName } = route.params;
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text style={{ fontSize: 20 }}>Details Screen</Text>
                <Text style={{ color: '#1ACB97' }}>ID: {userId}</Text>
                <Text style={{ color: '#1ACB97' }}>Name: {userName}</Text>
            </View>
        );
    }

    Note: In the DetailsScreen, we are accessing the same route parameters that we have passed in from HomeScreen.tsx.

    3 .ContactScreen.tsx

    import React from 'react';
    import { View, Button, Text, StyleSheet } from 'react-native';
    export function ContactScreen(props: any) {
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text style={{ fontSize: 20 }}>Contact Screen</Text>
            </View>
        );
    }

    React Native Navigation Examples

    In this section, we’ll walk you through some of the best examples of React Native navigation patterns. Explore these samples and leverage React Navigation libraries to achieve them.

    1. Stack navigator usage to navigate between screen components.
    2. Tab navigation usage in React Navigation.
    3. Drawer navigation usage in React Navigation.
    4. Passing parameters to screens in React Navigation.

    1. Using Stack Navigator to Navigate Between Screen Components 

    Start by making a /components folder in the root of your project. Then, make two files called Aboutscreen and Homescreen.js:

    // Homescreen.js
    import React, { Component } from 'react';
    import { Button, View, Text } from 'react-native';
    import { createStackNavigator, createAppContainer } from 'react-navigation';
    export default class Homescreen extends Component {
      render() {
        return (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Home Screen</Text>
              <Button
              title="Go to About"
              onPress={() => this.props.navigation.navigate('About')}
    />
          </View>
        )
      }
    }

    Remember the above onPress prop of the button as it will be explained what it does later.

    // Aboutscreen.js
    import React, { Component } from 'react';
    import { Button, View, Text } from 'react-native';
    import { createStackNavigator, createAppContainer } from 'react-navigation';
    export default class Aboutscreen extends Component {
      render() {
        return (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>About Screen</Text>
          </View>
        )
      }
    }

    The project folder should appear similar to what is shown in the below image:

    React Native Navigation Examples

    Now make some alterations to App.js. You will import what you require from react-navigation and execute the navigation there. It is crucial to execute your navigation in the root App.js file because the constituent obtained from App.js is the entrance point for a React Native application, and all the other components are descendants.

    As you shall notice, you will compress all the components inside the navigation functionalities:

    // App.js
    import React from 'react';
    import { StyleSheet, Text, View } from 'react-native';
    import { createStackNavigator, createAppContainer } from "react-navigation";
    import HomeScreen from './components/HomeScreen';
    import AboutScreen from './components/AboutScreen';
    export default class App extends React.Component {
      render() {
        return <AppContainer />;
      }
    }
    const AppNavigator = createStackNavigator({
      Home: {
        screen: HomeScreen
      },
      About: {
        screen: AboutScreen
      }
    });
    const AppContainer = createAppContainer(AppNavigator);
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      },
    });

    In the above design, createStackNavigator offers a route for your app to shift between screens, where each screen is put on top of a stack. It is constructed to contain a familiar Android and iOS feel and appearance: a new screen disappears from the bottom on Android and slides in from the right on iOS.

    Now it passes in a route outline entity to the createStackNavigator functionality. The Home route matches to the HomeScreen, and the About route matches to AboutScreen.

    Know that another, more brief way of coding the route outline is the { screen: HomeScreen } configuration setup.

    Additionally, you can optionally add other choices, as detailed by the API. If you wish to specify the original route, add a separate object:

    const AppNavigator = createStackNavigator({
        Home: {
          screen: HomeScreen
        },
        About: {
          screen: AboutScreen
        }
      },{
              initialRouteName: "Home"
      });

    You may have noticed that the Home and About route name-value pairs are enclosed by an overall route object. Remember, the options object isn’t enclosed but is a separate object.

    Behind the screen, the createStackNavigator function passes a navigation prop to the HomeScreen and AboutScreen components.

    However, the navigate prop streamlines navigation to a specified screen component that enables us to use it on a button at HomeScreen.js.

    On pressing it, you will see the AboutScreen page:

    <Button title="Go to About"
    onPress={() => this.props.navigation.navigate('About')}
    />

    In the App.js code, you finally developed an app container with const AppContainer = createAppContainer(AppNavigator);. The container handles the navigation state.

    To run the application, you will require to download the Expo client application. You can acquire the Android and iOS versions. Ensure the code is pointed to the project folder and execute the following command:

    npm start

    You can now notice a QR code shown on the terminal. Scan the code with the Expo application on Android, and for an iOS application, you may scan with the regular iPhone camera, which will give a command to click that will open the Expo application.

    2. Using Tab Navigation in React Navigation 

    A lot of mobile applications contain more than a single screen. A popular style of navigation in such applications is tab-based navigation.

    Here you will emphasize how to execute tab navigation by using createBottomTabNavigator.

    You can add another screen in the app by making a ContactScreen.js file under /components:

    import React, { Component } from 'react'
    export default class ContactScreen extends Component {
      render() {
        return (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Contact Screen</Text>
          </View>
        )
      }
    }

    Now you can add to the imports at the top of your App.js file:

    import ContactScreen from './components/ContactScreen';

    Remember that it is crucial to execute the navigation in the root App.js component. So, you will execute your tab navigation by introducing createBottomTabNavigator in App.js. Now replace createStackNavigator:

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

    Also substitute createStackNavigator with createBottomTabNavigator in the AppNavigator object:

    const AppNavigator = createBottomTabNavigator({
        Home: {
          screen: HomeScreen
        },
        About: {
          screen: AboutScreen
        }
      }, {
        initialRouteName: "Home"
      });

    Put the screen to the navigator object:

    const AppNavigator = createBottomTabNavigator({
        Home: {
          screen: HomeScreen
        },
        About: {
          screen: AboutScreen
        },
        Contact: {
          screen: ContactScreen
        }
      }, {
        initialRouteName: "Home"
      });

    If the app is run with npm start and launch it on the Expo client, you will see the bottom nav is now applied.

    3. Using Drawer Navigation in React Navigation 

    To start executing drawer navigation, swap createBottomTabNavigator in the command line with createDrawerNavigator.
    Begin at the import statements:

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

    Also upgrade the AppNavigator variable:

    const AppNavigator = createDrawerNavigator({
        Home: {
          screen: HomeScreen
        },
        About: {
          screen: AboutScreen
        },
        Contact: {
          screen: ContactScreen
        }
      }, {
          initialRouteName: "Home"
        });

    If you npm start, immediately see the alterations. Swipe from the left to observe the drawer nav.

    You can modify your drawer steering by setting icons alongside the route titles. In the folder for assets of the project, there are now three icons:

    Assets Folder – React Navigation

    You can modify by adding navigationOptions to the below screen component files:

    // in HomeScreen.js
    import React, { Component } from 'react';
    import { Button, View, Text, Image, StyleSheet } from 'react-native';
    import { createStackNavigator, createAppContainer } from 'react-navigation';
    export default class HomeScreen extends Component {
      static navigationOptions = {
        drawerLabel: 'Home',
        drawerIcon: ({ tintColor }) => (
          <Image
            source={require('../assets/home-icon.png')}
            style={[styles.icon, { tintColor: tintColor }]}
          />
        ),
      };
      render() {
        return (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Home Screen</Text>
            <Button
              title="Go to About"
              onPress={() => this.props.navigation.navigate('About')}
            />
          </View>
        )
      }
    }
    const styles = StyleSheet.create({
      icon: {
        width: 24,
        height: 24,
      }
    });
    // in AboutScreen.js
    import React, { Component } from 'react';
    import { Button, View, Text, Image, StyleSheet } from 'react-native';
    import { createStackNavigator, createAppContainer } from 'react-navigation';
    export default class AboutScreen extends Component {
      static navigationOptions = {
        drawerLabel: 'About',
        drawerIcon: ({ tintColor }) => (
         
        ),
      };
      render() {
        return (
         
            About Screen
         
        )
      }
    }
    const styles = StyleSheet.create({
      icon: {
        width: 24,
        height: 24,
      }
    });
    // in ContactScreen.js
    import React, { Component } from 'react';
    import { Button, View, Text, Image, StyleSheet } from 'react-native';
    export default class ContactScreen extends Component {
      static navigationOptions = {
        drawerLabel: 'Contact',
        drawerIcon: ({ tintColor }) => (
         
        ),
      };
      render() {
        return (
         
            Contact Screen
         
        )
      }
    }
    const styles = StyleSheet.create({
      icon: {
        width: 24,
        height: 24,
      }
    });

    The tintColor prop enables the application of any color according to active or inactive states of navigation labels and tabs. For instance, you can alter the active state color for your nav drawer labels. Head to the AppNavigator variable and put it to the options object:

    const AppNavigator = createDrawerNavigator({
        Home: {
          screen: HomeScreen
        },
        About: {
          screen: AboutScreen
        },
        Contact: {
          screen: ContactScreen
        }
      }, {
          initialRouteName: "Home",
            contentOptions: {
              activeTintColor: '#e91e63'
           }
        });

    These codes will lead to changing of colors.

    4. Passing Parameters to Screens in React Navigation

    There are easy methods of passing params to routes:

    Pass params to a route by placing them inside an object as another parameter to the navigation. navigate functionality:

    this.props.navigation.navigate('RouteName', { /* parameters go here */ })

    Study the params in the screen module:

    this.props.navigation.getParam(paramName, defaultValue)

    In your browser, you can connect to certain pages using an anchor <a> tag. When users click on a weblink, the address is pushed to the web browser history stack. When users click on the back button, the web browser shows the component from the stack’s top, so the initial page is now the formerly visited one. React Native does not contain an in-built idea of a global history stack such as a browser; now this is where React Navigation typescript becomes of use. React Navigation’s stack navigator executes a method of your app to shift between screens and sustain navigation history.

    An important difference between how this operates in a browser and React Navigation is that React Navigation’s stack navigator offers the animations and gestures required on Android and iOS gadgets when steering through screens or routes in the stack. For next steps, check out our blog posts about how to install and setup React Native on Ubuntu.  

    Looking to enhance your coding skills? Dive into the world of Python with our unique python certification training course. Unleash your potential and become a Python pro today!

    Conclusion

    In this guide, we have dived deep into React Navigation and learned how to navigate between screens. Besides, we have discussed the usage of React Navigation with the help of some examples. Use the concepts discussed in this guide to build dynamic, cross-platform applications for android and iOS. Enrol in KnowledgeHut React Native certification course to kickstart your journey and get started with React.

    Frequently Asked Questions (FAQs)

    1What is React Navigation?

    React Navigation is an impartial library that allows people to execute navigation functionalities in React Native apps. React Navigation is coded in JavaScript and doesn’t directly apply any native navigation API on Android and iOS. Instead, it reconstructs some subset of any API.

    2How Do I Set Up React Navigation?

    Passing parameters to a route by placing them inside an object as another parameter to the navigation. navigate function:

    this.props.navigation.navigate('RouteName', { /* parameters go here */ })
    3Is React Navigation Tough?

    If you already know about React Native, React, and JavaScript, then you can catch up with React Navigation quickly. However, if not, you are recommended to first gain some fundamental knowledge on React.

    4How Many Types of Navigation React Native?

    The three types of Navigations featured in Navigation React Native are TabNavigation, DrawerNavigation and StackNavigation.

    5How to Create a Navigation Bar in React Native?

    React Navigation bar is tabbed at the lower part of the screen, just below the header or as a header. Its use is to shift between different route screens. To create tab-based navigation, import createBottomTabNavigator and createAppContainer in the root functionalities of the react-navigation.

    Profile

    MD SOHAIL

    Author

    Sohail is an SRE, professionally experienced in IaaS, cloud computing, automation, and deployment. He is a python enthusiast and best-seller at Fiverr known for his result-driven deliverables and satisfactory customer service. He loves to experiment, write, and work out. When he is not actively involved in all these, he reads and explores new things.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon