Learn Expo · 3/11

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:

bash
npx create-expo-app@latest

If you are a brave soul adding it manually to an existing standard project, run:

bash
npx expo install expo-router react-native-safe-area-context react-native-screens expo-linking expo-constants expo-status-bar

Then, update your package.json to point to the router entry point:

json
{
  "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 /profile route.
  • app/settings/index.tsx ➡️ matches the /settings route.

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.

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.

tsx
// 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:

tsx
// 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, and router.back() to go back. Avoid router.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.

text
app/
 ├── (tabs)/
 │    ├── _layout.tsx
 │    ├── index.tsx      (Path becomes `/`)
 │    └── profile.tsx    (Path becomes `/profile`)

Here is how you define the <Tabs> layout:

tsx
// 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.

text
app/
 ├── user/
 │    └── [id].tsx 

Now, pass data to it using a link:

tsx
// 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.

tsx
// 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 that ID.


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:

  1. Main Tab Navigator (TabsLayout function):

    • This layout should be configured using the <Tabs> component.
    • It must contain three tabs:
      • An index route, which should display the title "Home".
      • A search route, with the title "Search".
      • A profile route, 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.
  2. Profile Stack Navigator (ProfileStackLayout function):

    • This layout should be configured inside the profile tab using the <Stack> component.
    • It must contain two screens:
      • An index screen, which should display the title "My Profile".
      • A dynamic route named post/[id], which should have the title "Post Details".

Expected result

Your completed code should define two React components that return Expo Router layout configurations.

  1. The TabsLayout function should return a <Tabs> component containing three <Tabs.Screen /> children.

    • The first screen should have name="index" and an options prop with { title: 'Home' }.
    • The second screen should have name="search" and an options prop with { title: 'Search' }.
    • The third screen should have name="profile" and an options prop with { title: 'Profile', headerShown: false }.
  2. The ProfileStackLayout function should return a <Stack> component containing two <Stack.Screen /> children.

    • The first screen should have name="index" and an options prop with { title: 'My Profile' }.
    • The second screen should be for the dynamic route, with name="post/[id]" and an options prop with { title: 'Post Details' }.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.