Navigation with Expo Router
8 min read
Setup and Boilerplate 🛠️
Before we map out our app, let's get the foundation installed. To get the latest version of Expo with Expo Router pre-configured, simply run this in your terminal:
npx create-expo-app@latestIf you are a brave soul adding it manually to an existing standard project, run:
npx expo install expo-router react-native-safe-area-context react-native-screens expo-linking expo-constants expo-status-barThen, update your package.json to point to the router entry point:
{
"main": "expo-router/entry"
}1. File-Based Routing: The Expo Router Paradigm 📁
Definition: File-based routing is a system where the physical folder and file structure of your project automatically determines the navigation routes of your application.
The Problem: Historically in React Native, setting up navigation meant importing libraries and writing massive, complex JavaScript configuration objects. You had to manually map string names to components. If you renamed a component but forgot to update the massive central routing object, your app crashed. It was essentially writing a 500-line map that looked like a bowl of spaghetti just to move from "Home" to "Settings".
The Solution: Expo Router removes the central configuration object entirely. Instead, whenever you add a file inside the app directory, it instantly becomes a screen in your app. The file system is the configuration.
How it works under the hood: Expo Router is actually built directly on top of React Navigation. When your app compiles, Expo Router aggressively scans your app directory and automatically generates those exact React Navigation objects for you. You get the robust performance of React Native's standard library without the mental breakdown of maintaining it.
Real-Life Scenario: Think of a modern office building. If an employee (the router) needs to find the HR department (the screen), they don't need to consult a constantly changing, hand-written master ledger at the front desk. They just walk to Floor 2, Room 4 (app/floor2/room4.tsx), because the physical structure itself directly dictates where everything is located.
Hands-on: The Basic Rules
If you create a folder called app, Expo Router maps files to paths exactly like a website:
app/index.tsx➡️ matches the/route (Your Home Screen).app/profile.tsx➡️ matches the/profileroute.app/settings/index.tsx➡️ matches the/settingsroute.
The Magic of _layout.tsx
Files named _layout.tsx are special. They do not represent a single screen. Instead, they represent a UI wrapper around all the screens in that same directory. If you want a navigation header to appear on every screen in a folder, you put it in the _layout.tsx.
// app/index.tsx
import { Text, View } from 'react-native';
export default function Home() {
return (
<View>
<Text>Welcome to the easiest routing experience of your life.</Text>
</View>
);
}2. Stack Navigation: Moving Between Screens and Modals 🥞
Definition: Stack Navigation is a navigation pattern where new screens are placed on top of a stack, and navigating backwards removes the top screen to reveal the one underneath.
The Problem: When users click on a tweet to see its replies, they expect the new screen to slide in smoothly. More importantly, when they hit the "Back" button on their phone, they expect to return to the exact spot on their timeline. Without a stack system, managing the "history" of where a user has been and animating between those screens is a chaotic nightmare.
The Solution: The <Stack> component automatically tracks navigation history, provides a native header bar (with a built-in back button), and handles iOS/Android specific slide animations out of the box.
Real-Life Scenario: Think of a physical deck of cards or reading a book. When you click a link, you deal a new card on top of the deck. You can only interact with the top card. When you are done, you throw that card away (pop it off the stack), and the previous card is exactly where you left it.
Hands-on: Using Stacks
In your _layout.tsx, you define the Stack. Then, you can use the <Link> component or the useRouter hook inside your screens to move between files.
// app/_layout.tsx
import { Stack } from 'expo-router';
export default function RootLayout() {
return (
<Stack>
{/* You can configure specific screens by matching their filename */}
<Stack.Screen name="index" options={{ title: 'Home' }} />
<Stack.Screen name="about" options={{ title: 'About Us' }} />
{/* Modals are just screens that slide up from the bottom! */}
<Stack.Screen
name="settingsModal"
options={{ presentation: 'modal', title: 'Settings' }}
/>
</Stack>
);
}To trigger a navigation:
// app/index.tsx
import { View, Button } from 'react-native';
import { useRouter, Link } from 'expo-router';
export default function Home() {
const router = useRouter();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{/* Method 1: The Link component (Great for simple buttons/text links) */}
<Link href="/about">Go to About Screen</Link>
{/* Method 2: Imperative routing (Great for navigating after an API call or logic) */}
<Button
title="Open Settings"
onPress={() => router.push('/settingsModal')}
/>
</View>
);
}Industry Standard: Always use
router.push()to add to the stack, androuter.back()to go back. Avoidrouter.replace()unless you specifically want to destroy the history (e.g., navigating a user away from a Login screen so they can't press back to return to it once authenticated).
3. Tab Navigation: Creating Bottom Tab Layouts 🗂️
Definition: Tab Navigation is a layout pattern that places a persistent row of buttons (tabs) usually at the bottom of the screen, allowing users to switch contexts without losing the state of each context.
The Problem: If your app has three major, unrelated sections—like an Instagram Feed, Search, and Profile—forcing users to hit the "Back" button ten times just to go from a deep profile view back to the main feed will result in users uninstalling your app out of sheer frustration.
The Solution: Bottom tabs keep multiple stacks running in parallel. Tapping a tab instantly switches the view, preserving wherever you left off in the previous tab.
Real-Life Scenario: Imagine you are cooking in a kitchen. You have three stations: a cutting board, a stove, and a sink. You don't put the cutting board away into a cupboard every time you need to stir the soup. You just turn around. Tabs are your kitchen stations—they stay exactly as you left them, ready for you to switch between them instantly.
Hands-on: Route Groups and Tabs
To prevent the word tabs from showing up in your URL string (like myapp.com/tabs/profile), Expo Router uses Route Groups. Any folder wrapped in parentheses ( ) is completely ignored by the URL path but still groups the files logically together in your project.
Create a folder called (tabs). Inside it, put a _layout.tsx and your screens.
app/
├── (tabs)/
│ ├── _layout.tsx
│ ├── index.tsx (Path becomes `/`)
│ └── profile.tsx (Path becomes `/profile`)Here is how you define the <Tabs> layout:
// app/(tabs)/_layout.tsx
import { Tabs } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
export default function TabLayout() {
return (
<Tabs screenOptions={{ tabBarActiveTintColor: 'blue' }}>
<Tabs.Screen
name="index"
options={{
title: 'Home feed',
tabBarIcon: ({ color }) => <Ionicons name="home" size={24} color={color} />
}}
/>
<Tabs.Screen
name="profile"
options={{
title: 'My Profile',
tabBarIcon: ({ color }) => <Ionicons name="person" size={24} color={color} />
}}
/>
{/* Hide a screen from the tab bar entirely but keep it in the layout stack */}
<Tabs.Screen
name="hiddenPage"
options={{ href: null }}
/>
</Tabs>
);
}4. Dynamic Routes: Passing and Reading Parameters 🏷️
Definition: Dynamic routes are template route files that can capture variable segments of a URL and pass them into the component as parameters.
The Problem: Imagine you are building an e-commerce app with 10,000 pairs of shoes. You cannot manually create shoe-1.tsx, shoe-2.tsx, all the way down to shoe-10000.tsx. It is physically impossible and fundamentally absurd.
The Solution: You create a single file wrapped in brackets, like [id].tsx. When a user navigates to /shoe/999, Expo Router intercepts the request, loads the [id].tsx file, and hands it the value 999 so the screen knows exactly which shoe to fetch from your database.
Real-Life Scenario: Think of a blank "Hello, My Name Is:" sticker at a networking event. The physical sticker format itself is the dynamic route ([name].tsx). When a guest arrives, they write their specific name on it (the parameter). The layout is completely identical for every single guest, only the data displayed changes.
Hands-on: Brackets and Hooks
Create a folder for your entity, for example, user, and inside it create [id].tsx.
app/
├── user/
│ └── [id].tsx Now, pass data to it using a link:
// From somewhere in your app...
<Link href="/user/42">View User 42</Link>
// Or dynamically with imperative routing:
const userId = 88;
router.push(`/user/${userId}`);Inside [id].tsx, you use the useLocalSearchParams() hook to read that data.
// app/user/[id].tsx
import { View, Text } from 'react-native';
import { useLocalSearchParams } from 'expo-router';
export default function UserProfile() {
// The property name perfectly matches the filename inside the brackets [id]
const { id } = useLocalSearchParams();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 24 }}>Welcome, User #{id}!</Text>
<Text>Fetching data for user {id}...</Text>
</View>
);
}Industry standard: Data passed through route parameters should be strictly minimal (like string IDs or tiny tokens). Do not attempt to pass massive JSON objects through routing parameters. Pass the
ID, and let the target screen fetch the complex data it needs using thatID.
Reference & Further Reading 📚
Challenge
Challenge: Configure a Nested Navigation Layout
Your task is to implement the navigation structure for a simple social media application using Expo Router's declarative layout components. You will configure a main Tab navigator and a nested Stack navigator.
Requirements:
Main Tab Navigator (
TabsLayoutfunction):- This layout should be configured using the
<Tabs>component. - It must contain three tabs:
- An
indexroute, which should display the title "Home". - A
searchroute, with the title "Search". - A
profileroute, with the title "Profile". For this tab, the default header should be hidden, as it will contain its own nested stack navigator with a header.
- An
- This layout should be configured using the
Profile Stack Navigator (
ProfileStackLayoutfunction):- This layout should be configured inside the
profiletab using the<Stack>component. - It must contain two screens:
- An
indexscreen, which should display the title "My Profile". - A dynamic route named
post/[id], which should have the title "Post Details".
- An
- This layout should be configured inside the
Expected result
Your completed code should define two React components that return Expo Router layout configurations.
The
TabsLayoutfunction should return a<Tabs>component containing three<Tabs.Screen />children.- The first screen should have
name="index"and anoptionsprop with{ title: 'Home' }. - The second screen should have
name="search"and anoptionsprop with{ title: 'Search' }. - The third screen should have
name="profile"and anoptionsprop with{ title: 'Profile', headerShown: false }.
- The first screen should have
The
ProfileStackLayoutfunction should return a<Stack>component containing two<Stack.Screen />children.- The first screen should have
name="index"and anoptionsprop with{ title: 'My Profile' }. - The second screen should be for the dynamic route, with
name="post/[id]"and anoptionsprop with{ title: 'Post Details' }.
- The first screen should have