Stack navigator
- React Native course
- Beginner
- Lesson 89/116
- 5 min
Learn page transitions with the Stack navigator.
Stack navigator
A stack navigator manages screens like a stack of cards. When a new screen opens it is pushed on top; when you go back the top screen is popped. This is the most common navigation pattern in mobile apps.
To create a stack you call createNativeStackNavigator. It returns two components: Stack.Navigator (the wrapper) and Stack.Screen (for each screen). You place multiple Stack.Screen entries inside Stack.Navigator.
Navigator and Screen
The Stack.Navigator component is the wrapper for all screens. Inside it you place a Stack.Screen for each screen. Each Stack.Screen takes name (screen name) and component attributes.
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>The first listed screen is the initial screen shown when the app opens. The name value is the string key you use in navigate calls.
Practice Your turn: create a two-screen stack
Import createNativeStackNavigator and assign it to a Stack variable. Inside Stack.Navigator add two Stack.Screen entries named Home and Details.
Starter code
// import the stack creator
// assign it to a Stack variable
// add two Screens inside the NavigatorSample solution
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
function App() {
return (
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: create the Stack
const Stack = ____();
const Stack = createNativeStackNavigator();
Explanation: createNativeStackNavigator is called.
2 What are the required attributes of Stack.Screen?
<Stack.Screen name="Home" component={HomeScreen} />- style and theme
- route and params
- title and color
- name and component Correct answer
Explanation: name sets the screen key and component sets the rendered component.
3 Match: component and role
| Term | Meaning |
|---|---|
Stack.Navigator |
screen wrapper |
Stack.Screen |
a single screen |
NavigationContainer |
root wrapper |