React Native
Navigation
Combine two screens with Stack navigation.
Adding navigation
The app can now add items. Now we will add navigation to later transition to a details screen. We import NavigationContainer from @react-navigation/native and createNativeStackNavigator from @react-navigation/native-stack.
We rename the current App component to HomeScreen. We define a new App component and put NavigationContainer and Stack.Navigator inside. We register HomeScreen with Stack.Screen. This way the app has a navigation stack.
Registering Stack.Screen
Inside Stack.Navigator you place a Stack.Screen for each screen. Each Stack.Screen takes name (screen name) and component attributes. The first registered screen is the initial screen shown when the app opens.
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
Here the HomeScreen component is registered with the name Home. Later you can return to this screen with navigation.navigate('Home'). The name value is the key used in navigation calls.
Exercise Your turn: set up navigation
Import NavigationContainer from @react-navigation/native and createNativeStackNavigator from @react-navigation/native-stack. Assign createNativeStackNavigator() to a Stack variable. Write a new App component; inside it place <NavigationContainer> and <Stack.Navigator>, add <Stack.Screen name="Home" component={HomeScreen} />.
Show example solution
import { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
function HomeScreen() {
const [text, setText] = useState('');
const [items, setItems] = useState([]);
return (
<View style={styles.container}>
<Text>Shopping List</Text>
<TextInput value={text} onChangeText={setText} placeholder="Item name" style={styles.input} />
<Button title="Add" onPress={() => setItems([...items, text])} />
</View>
);
}
const Stack = createNativeStackNavigator();
const styles = StyleSheet.create({
container: { flex: 1, padding: 16 },
input: { borderWidth: 1, padding: 8, marginBottom: 8 },
});
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
Test yourself
-
Match: component and role
- NavigationContainer
- root wrapper
- Stack.Navigator
- screen wrapper
- Stack.Screen
- single screen
-
What does NavigationContainer do?
<NavigationContainer>...</NavigationContainer>
- Displays text
- Defines styles
- Stores data
- It is the root navigation wrapper
Show answer
It is the root navigation wrapper — NavigationContainer is the root navigation wrapper.
-
Fill in the blank: import NavigationContainer
import { ____ } from '@react-navigation/native';
Show answer
import { NavigationContainer } from '@react-navigation/native';
Next lesson: Putting it together