Stack navigation
Displaying screens in a Stack is the default way to navigate. It means that when you navigate to a new screen, it is rendered on top of the current screen, so you can goBack()
to the previous screen to go back.
Let's create two more screens: the counter and idea.
New file: app/counter.tsx
import { Text, View, StyleSheet } from "react-native";
export default function CounterScreen() {
return (
<View style={styles.container}>
<Text style={styles.text}>Counter</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff",
},
text: {
fontSize: 24,
},
});
New file: app/idea.tsx
import { Text, View, StyleSheet } from "react-native";
export default function IdeaScreen() {
return (
<View style={styles.container}>
<Text style={styles.text}>Idea</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
text: {
fontSize: 24,
},
});
Ways to navigate
There are 3 main ways to navigate between screens:
- Using the
Link
component - Programmatically with the
useRouter
hook - Using the built-in header and bottom tabs button
Navigate between screens
Let's try out all three. First use the Link
component in index.tsx to navigate to the counter screen:
Update: app/index.tsx
@@ -1,10 +1,17 @@
import { StyleSheet, View } from "react-native";
import { theme } from "../theme";
import { ShoppingListItem } from "../components/ShoppingListItem";
+import { Link } from "expo-router";
export default function App() {
return (
<View style={styles.container}>
+ <Link
+ href="/counter"
+ style={{ textAlign: "center", marginBottom: 18, fontSize: 24 }}
+ >
+ Go to /counter
+ </Link>
<ShoppingListItem name="Coffee" />
<ShoppingListItem name="Tea" isCompleted />
<ShoppingListItem name="Milk" isCompleted />
Then in the counter screen, use the useRouter
hook to navigate to the idea screen:
Update: app/counter.tsx
@@ -1,8 +1,16 @@
-import { Text, View, StyleSheet } from "react-native";
+import { useRouter } from "expo-router";
+import { Text, View, StyleSheet, TouchableOpacity } from "react-native";
export default function CounterScreen() {
+ const router = useRouter();
+
return (
<View style={styles.container}>
+ <TouchableOpacity onPress={() => router.navigate("/idea")}>
+ <Text style={{ textAlign: "center", marginBottom: 18, fontSize: 24 }}>
+ Go to /idea
+ </Text>
+ </TouchableOpacity>
<Text style={styles.text}>Counter</Text>
</View>
);
And finally we can use the header buttons to navigate back.
Checkpoint
You might have noticed that the navigation UI looks a bit different between iOS and Android. The default animations and gestures make this especially obvious. This is by design as we want out apps to feel native to the platform.