Stack Navigator

📡 What you will learn

  • Organise your routes and name your screens.
  • How to use the react-navigation library with the navigation prop.

👾 Before we start the exercise

  • There are others routing solutions available, keep in mind we are using react-navigation library.
  • We are using the last version of react-navigation (Be carreful when you randomly copy/paste Stack Overflow).
  • TypeScript definitions are a bit complicated with react-navigation, for now just ignore them.

Here is a preview of our application user flow:

react-navigation

👨‍🚀 Exercise 1

Installation

  • Read the Getting started guide to:
    1. Install the required packages in your React Native project.
    2. Install dependencies into an Expo managed project.

🔭 Hint: you just installed the core packages, for every type of navigator (Native Stack, Drawer, Bottom Tabs…) you will need to install other packages.

Organise your routes

We are going to create a "sitemap" of all our routes. This will help-us to have a single source of truth.

We will use a TypeScript feature called const assertions.

// ./src/navigation/Routes.ts

const Routes {
  LOGIN_SCREEN = 'Login',
  TERMS_SCREEN = 'Terms',
  STARSHIP_FEED_SCREEN = 'Starships',
  STARSHIP_DETAIL_SCREEN = 'Starship',
} as const;
  • Create a Routes.ts file in ./src/navigation/

Create a Navigator file

  • Create a new component called Navigator.tsx on ./src/navigation/Routes.ts and update the entry point of your application, such as App.tsx.
  • Wrap your Stack with a NavigationContainer.

Create your first Stack

  • Read the Stack.Navigator documentation.
  • Create a Stack Navigator in ./src/navigation/Navigator.tsx that shows the LoginScreen and the TermsScreen.
  • Use LOGIN_SCREEN and TERMS_SCREEN from Routes.tsas screen names to maintain consistency when navigating

🔭 Hint: You can have multiple functions in the same file.

Navigate to another screen

Do you remeber the <Text> "by login you accept the Terms and Conditions."? We will use the navigate() function to go to another screen.

react-navigation

  • Wrap the terms link with a
<TouchableOpacity onPress={navigateToTerms}>
  ...
</TouchableOpacity>

Here is a function to navigate between screens:

function navigateToTerms() {
  navigation.navigate('Routes.TERMS_SCREEN');
}
  • Add a goBack behavior on TermsScreen.tsx

Options for screens

  • On the TermsScreen, we have an issue with the double header, we can fix it with some options within the Navigator
<Stack.Navigator screenOptions={{ headerShown: false }}>
  ...
</Stack.Navigator>