logo

Introducing React Navigation 5

March 23, 2020

react-navigation

React Navigation is the closest navigation library to come in mind when we are talking about the navigation in React Native, I’m a big fan of this library and my first solution to handle the Navigation in React Native, it has an awesome and easy API, very customizable. version 5 just went from beta to stable. and it comes with some features changes and new API design that is a simple and different way to declare the Routes. In this article, we are going through the new APIs and ways to use them in our applications.

Installing

The way of Installing react-navigation changed a little bet compared to previous versions (>4.x)

// > 4.x verions
yarn add react-navigation

Installing React Navigation 5 will look like this.

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

The latest versions of React Navigation use many third parties library like react-native-gesture-handler for animation and the handling of the transitions. so you always need to install those libraries.

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

Dynamic screens

The new API introduces the dynamism in initializing the Routes. previously it was a static way, basically, we had to define our Routes in a config file.

// @flow
import React from "react";

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


/** ---------Screens----------- */
// import LaunchScreen from "../Containers/LaunchScreen";
import HomeScreen from "../Containers/HomeScreen";

import ProfileScreen from "../Containers/ProfileScreen";
import LoginScreen from "../Containers/LoginScreen";






const StackNavigator = createStackNavigator(
  {
    initialRouteName: "Home"
  },
  {
    Home: {
      screen: HomeScreen
    },
     Login: {
      screen: LoginScreen,
      headerMode: "none",

    },
      Profile: {
      screen: ProfileScreen
    }



);

export default createAppContainer(StackNavigator);

The new API comes with dynamic components. and made the navigation to be more dynamic. The new way to declare the Routes will be much like the following.

import React from "react"
import { SafeAreaView, StyleSheet, View, Text, StatusBar } from "react-native"

import { NavigationContainer } from "@react-navigation/native"
import { createStackNavigator } from "@react-navigation/stack"

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView style={styles.containerStyle}>
        <AppNavigation />
      </SafeAreaView>
    </>
  )
}
const Stack = createStackNavigator()
const AppNavigation = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="home">
        <Stack.Screen name="home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}
const HomeScreen = () => {
  return (
    <View style={styles.containerStyle}>
      <Text style={styles.title}>Home Screen</Text>
    </View>
  )
}

react-navigation-5

This new way is dynamic, more simple to use, it kinda similar to react-router API.

Dynamic options

This is the most requested feature by the community for a long time. I always had issues with the old method (static)and it was really hard to change the navigation behavior dynamically.

The old method => < 4.x

With older versions of react-navigation we had to define static options. and there was no way to change this dynamically.

  static navigationOptions = {
    title: "Sign In",
    header: null,
    mode: "modal",
    headerMode: "none"
  };

The new method (version 5)

React-navigation comes with a dynamic way and simple, we can set the options to any screen using just props.

const AppNavigation = ({}) => {
  let auth = {
    authenticated: true,
    user: {
      email: "user@mail.com",
      username: "John",
    },
  }
  let ProfileScreenTitle = auth.authenticated ? auth.user.username : "Profile"
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen
          name="Profile"
          component={ProfileScreen}
          options={{
            title: ProfileScreenTitle,
            headerTintColor: "#4aa3ba",
            headerStyle: {
              backgroundColor: darkModeOn ? "#000" : "#fff",
            },
          }}
        />
        <Stack.Screen name="About" component={AboutScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

image

With dynamic options, I can change the title based on authentication for example if the user is authenticated I can set the screen title to be the user’s username, I can change the backgroundColor for the header. this is more useful especially if you are using dynamic themes or if you are willing to implement the dark mode in your app.

Hooks

This is my favorite feature so far, it’s a time-saver, the new API introduced some custom hooks to perform certain actions.

In the previous versions for example if I have to get the currentName of the active screen, I had to create some helpers to do that for me pretty much like the following.

export function getCurrentRouteName(): string | null {
  const tag = "[getCurrentRouteNameSync] "
  const navState = getStore().getState().nav
  const currentRoute = getActiveRouteState(navState)
  console.log(tag + " currentRoute > ", currentRoute)
  return currentRoute && currentRoute.routeName ? currentRoute.routeName : null
}

The hooks API avoid me all these things and made it more easy for me to access the Navigation API with one single line using a hook.

Now I can easily get the RouteName using useRoute Hook.

import { useRoute } from "@react-navigation/native"
const AboutScreen = ({ navigation }) => {
  const route = useRoute()
  return (
    <View
      style={{
        justifyContent: "space-around",
        flex: 1,
        alignItems: "center",
      }}
    >
      {/*    Display the RouteName here */}
      <Text style={styles.title}>{route.name}</Text>
    </View>
  )
}

The same thing we can do with useNavigationState Hook. that gives us access to the navigation state.

const navigationState = useNavigationState(state => state)
let index = navigationState.index
let routes = navigationState.routes.length
console.log(index)
console.log(routes)

React Navigation offer other hooks as well for example:

  • useFocuseEffect : It’s a side effect hook that’s the screens are loaded, it returns the focused screen
  • useLinking: to handle the deepLinking

I highly recommend you check them out.

Wrapping Up

The new React-navigation API definitely moved from a static way to dynamic. it’s a great movement that will absolutely change the way we handle the navigation in React Native. dynamic Routes were a major request by the react-navigation users the new way will help us to create a better user navigation experience.

Thanks for reading