Stack Navigator
📡 What you will learn
- Organise your routes and name your screens.
- How to use the
react-navigation
library with thenavigation
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:
👨🚀 Exercise 1
Installation
- Read the Getting started guide to:
- Install the required packages in your React Native project.
- 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 asApp.tsx
. - Wrap your
Stack
with aNavigationContainer
.
Create your first Stack
- Read the
Stack.Navigator
documentation. - Create a Stack Navigator in
./src/navigation/Navigator.tsx
that shows theLoginScreen
and theTermsScreen
. - Use
LOGIN_SCREEN
andTERMS_SCREEN
fromRoutes.ts
as screen names to maintain consistency when navigating
🔭 Hint: You can have multiple function
s 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.
- 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 onTermsScreen.tsx
Options for screens
- On the
TermsScreen
, we have an issue with the double header, we can fix it with some options within theNavigator
<Stack.Navigator screenOptions={{ headerShown: false }}>
...
</Stack.Navigator>