Native Stack Navigator

Learn via video courses
Topics Covered

Overview

Smooth navigation is crucial for modern mobile applications, as it directly impacts user engagement and satisfaction. Native Stack Navigator simplifies navigation implementation in React Native, providing performance optimizations and seamless integration with the native platform. It enables developers to create fluid and intuitive navigation flows, enhancing user experiences and driving the success of their applications. In this article, we will explore the benefits and implementation of Native Stack Navigator, empowering developers to deliver exceptional navigation experiences in React Native.

Introduction

The Native Stack Navigator is a feature provided by React Navigation, as we have discussed in the overview section it enables smooth transitions between screens in your application. The Native part refers to the fact that it uses the native navigation capabilities provided by the underlying platform (iOS or Android) to deliver a smoother and more performant navigation experience for users. It utilizes the native APIs UINavigationController on iOS and Fragment on Android, ensuring that the navigation experience is consistent and performs similarly to apps developed natively on those platforms. Additionally, it offers basic support for web applications using react-native-web. It is important to note that while the Native Stack Navigator provides native performance and incorporates native features like a large title on iOS, it may have limited customization options compared to the @react-navigation/stack.

Installation

To install the Native Stack Navigator in your React Native project, follow the below steps:

First we will be creating a new React Native project, I am using Expo to create a react native project.

  • Install the Expo CLI globally on your machine if you haven't already. Open your terminal and execute one of the following commands based on your package manager preference:

    For Yarn users:

    For npm users:

  • Create a new Expo project by running the following command:

    For Yarn users:

    For npm users:

To install native stack navigator in this project open a terminal window and execute one of the following commands based on your package manager preference:

For Yarn users:

For npm users:

This command will install the Native Stack Navigator package along with its dependencies.

After the installation is complete, you need to link any native dependencies that come with the package. Run the following command:

For Yarn users:

For npm users:

This command will link the necessary native dependencies to your project.

API Definition

You can start using the Native Stack Navigator in your React Native project. Import it into your code like this:

Props

The Stack.Navigator component provides several props that can be utilized:

id (Optional): This prop allows for the assignment of a unique identifier to the navigator. It can be employed with navigation.getParent to reference this specific navigator within a child navigator.

initialRouteName: With this prop, developers can specify the name of the route that should be rendered when the navigator is initially loaded.

screenOptions: This prop enables the definition of default options that will be applied to the screens within the navigator.

Options

Here are the available options for configuring the screens in the navigator:

title:

  • A string that can serve as a fallback for the headerTitle.

headerBackButtonMenuEnabled:

  • A boolean value that determines whether the menu should be displayed when the back button on iOS >= 14 is long-pressed. By default, it is set to true.
  • Note: This option requires react-native-screens version >=3.3.0 and is only supported on iOS.

headerBackVisible:

  • Controls the visibility of the back button in the header. It can be used to display a back button alongside the headerLeft if it has been specified.
  • This option does not affect the first screen in the stack.

headerBackTitle:

  • Specifies the title string to be used for the back button on iOS. If not provided, it defaults to the title of the previous scene. If there is insufficient space, it is set to "Back". To hide the back button title, set headerBackTitleVisible to false.
  • Note: This option is only supported on iOS.

headerBackTitleVisible:

  • Determines whether the back button title should be visible or not.
  • Note: This option is only supported on iOS.

headerLargeStyle:

  • Defines the style of the header when a large title is displayed. The large title appears when headerLargeTitle is set to true and any scrollable content reaches the corresponding edge of the header.
  • Supported properties:
    • backgroundColor (only applicable on iOS)

headerLargeTitle:

  • Determines whether to enable a header with a large title that collapses to a regular header when scrolling.
  • To enable the collapsing of the large title on scroll, the screen's content should be wrapped in a scrollable view like ScrollView or FlatList. If the scrollable area does not fill the screen, the large title will not collapse on the scroll. Additionally, make sure to specify contentInsetAdjustmentBehavior="automatic" in your ScrollView, FlatList, or similar components.
  • Only supported on iOS.

headerLargeTitleShadowVisible:

  • Controls the visibility of the drop shadow for the header when a large title is displayed.

headerBackTitleStyle:
This option allows you to specify a style object for the header back title. Supported properties include font family and fontSize. Note: This option is only supported on iOS.

headerBackImageSource:
You can provide an image to display in the header as the icon in the back button. By default, it uses the back icon image appropriate for the platform: A chevron on iOS An arrow on the Android

HeaderTransparent:
This option is a boolean value that determines whether the navigation bar is translucent. By default, it is set to false. When set to true, the header becomes positioned, floating over the screen and overlapping the content underneath. The background color of the header becomes transparent unless specified in the headerStyle. This feature is particularly useful when you want to render a semi-transparent header or a blurred background.

Note that if you don't want your content to appear under the header, you must manually add a top margin to your content. React Navigation does not handle this automatically.

To get the height of the header, you can use the HeaderHeightContext with React's Context API or utilize the useHeaderHeight hook.

HeaderBlurEffect:
The headerBlurEffect option applies a blur effect to the translucent header. For this effect to work, the headerTransparent property must be set to true. There are several supported values for headerBlurEffect, including extraLight, light, dark, regular, prominent, systemUltraThinMaterial, and systemThinMaterial.

headerBackground:
The headerBackground option is a function that returns a React Element to be rendered as the background of the header. This is particularly useful when you want to use backgrounds like images or gradients.

headerTintColor:
The headerTintColor option allows you to specify the tint color for the header. It affects the color of both the back button and the title in the header.

headerLeft:
The headerLeft option is a function that returns a React Element to be displayed on the left side of the header. It replaces the default back button. If you want to show the back button alongside the left element, you can refer to the headerBackVisible option.

headerRight:
The headerRight option is a function that returns a React Element to be displayed on the right side of the header.

headerTitle:
The headerTitle option can be either a string or a function that returns a React Element. By default, it uses the title or name of the screen. When a function is passed, it receives the tintColor and children as arguments in the options object. The title string is available as the children prop.

Events

The navigator can emit events based on specific actions. The following events are supported:

transitionStart

This event is triggered when the transition animation begins for the current screen.

Event data:

e.data.closing - A Boolean value indicating whether the screen is being opened or closed.

Example:

transitionEnd

This event is triggered when the transition animation concludes for the current screen.

Event data:

e.data.closing - A Boolean value indicating whether the screen was opened or closed.

Example:

Please note that the code snippets provided above demonstrate the usage of event listeners for the specified events, allowing developers to execute custom actions when these events occur.

Helpers

  • replace The method is used to replace the current screen in the stack with a new screen. It takes two arguments:

    • name (string): The name of the route to be pushed onto the stack.
    • params (object): Optional screen parameters to pass to the destination route.

Example usage:

  • push The push method is used to push a new screen to the top of the stack and navigate to it. It accepts the following arguments:

    • name (string): The name of the route to be pushed onto the stack.
    • params (object): Optional screen parameters to pass to the destination route.

Example usage:

  • pop This method is used to remove the current screen from the stack and navigate back to the previous screen. It can also take an optional argument count, specifying how many screens to pop back by.

Example usage:

  • popToTop The popToTop method is used to remove all screens in the stack except the first one and navigate to it.

Example usage:

Example

Let's create a React native application to demonstrate the usage of the native stack navigator. We will be creating two screens Home and Profile, native stack navigator to switch between these screens.

Paste the below code in the App.js file:

Let's step by step go through the code:

Import necessary components: createStackNavigator from @react-navigation/stack is imported to create the stack navigator. NavigationContainer from @react-navigation/native is imported to wrap the app with the navigation container.

Create a stack navigator: The createStackNavigator function is used to create a stack navigator instance, stored in the Stack variable.

Define screen components: Two screen components, HomeScreen and ProfileScreen, are created using functional components. The ProfileScreen component receives the route prop, which contains the params passed during navigation.

Wrap the app with NavigationContainer: The root component, App, is wrapped with the NavigationContainer component, which provides the navigation context.

Configure stack navigator screens: Inside the NavigationContainer, the Stack.Navigator component is used to define the screens within the stack navigator. Each screen is defined using Stack.Screen, specifying the name, corresponding component, and optional configuration options.

Home screen configuration: The HomeScreen component is added as a screen in the stack navigator using Stack.Screen. The name prop is set as Home, the component prop is set as HomeScreen, and the options prop is used to configure the screen's title.

Profile screen configuration: The ProfileScreen component is added as a screen in the stack navigator using Stack.Screen. The name prop is set as Profile, the component prop is set as ProfileScreen, and the options prop is used to configure the screen's title.

Output Profile screen configuration

Conclusion

  • Native Stack Navigator is a powerful navigation library for React Native that provides a native feel and performance to navigation in mobile apps.
  • It offers a seamless transition between screens, smooth animations, and better memory management compared to JavaScript-based navigators.
  • Native Stack Navigator integrates directly with the native navigation libraries of iOS and Android, leveraging their native capabilities.
  • The installation process for Native Stack Navigator is straightforward and can be done using either yarn or npm.
  • By using Native Stack Navigator, developers can create high-quality and performant navigation experiences for their React Native apps.
  • It is a popular choice among React Native developers due to its reliability, performance, and close integration with the native platforms.