Master file-based routing with Expo Router: stacks, tabs, and nested navigation.
Expo Router Overview
Expo Router brings file-based routing (like Next.js) to React Native. Routes map directly to files in the app/ directory.
app/
├── _layout.tsx # Root layout (required)
├── index.tsx # Home route: /
├── _layout.tsx # Layout for this directory
├── about.tsx # Route: /about
├── settings.tsx # Route: /settings
├── (auth)/ # Route group (no URL segment)
│ ├── _layout.tsx
│ ├── login.tsx # Route: /login
│ └── register.tsx # Route: /register
├── (app)/ # Route group
│ ├── _layout.tsx # Tab layout
│ ├── index.tsx # Route: / (tab 1)
│ ├── profile.tsx # Route: /profile (tab 2)
│ └── settings.tsx # Route: /settings (tab 3)
├── movie/
│ ├── [id].tsx # Dynamic route: /movie/123
│ └── _layout.tsx
└── +not-found.tsx # 404 handler
Root Layout
// app/_layout.tsx
import { Stack } from 'expo-router';
import { Providers } from '@/providers';
export default function RootLayout() {
return (
<Providers>
<Stack
screenOptions={{
headerShown: false,
// Default transitions
animation: 'slide_from_right',
}}
>
{/* Static routes */}
<Stack.Screen name="index" />
<Stack.Screen name="about" />
{/* Dynamic routes */}
<Stack.Screen name="movie/[id]" />
{/* Route groups - no URL segment */}
<Stack.Screen name="(auth)" />
<Stack.Screen name="(app)" />
</Stack>
</Providers>
);
}Stack Navigation
// app/_layout.tsx (Stack)
import { Stack } from 'expo-router';
export default function StackLayout() {
return (
<Stack>
<Stack.Screen
name="index"
options={{ title: 'Home', headerStyle: { backgroundColor: '#3b82f6' } }}
/>
<Stack.Screen
name="details"
options={{ title: 'Details' }}
/>
<Stack.Screen
name="profile"
options={{
headerRight: () => <Button title="Edit" onPress={() => {}} />,
}}
/>
</Stack>
);
}Navigating in Stack
import { Link, useRouter } from 'expo-router';
import { Pressable, Text, StyleSheet } from 'react-native';
// Declarative: Link component
export function HomeScreen() {
return (
<View style={styles.container}>
<Link href="/details" className={styles.link}>
<Text style={styles.linkText}>Go to Details</Text>
</Link>
<Link href="/movie/123" className={styles.link}>
<Text style={styles.linkText}>View Movie 123</Text>
</Link>
{/* Replace current screen (no back) */}
<Link href="/login" replace className={styles.link}>
<Text style={styles.linkText}>Login (replace)</Text>
</Link>
</View>
);
}
// Imperative: useRouter hook
export function LoginScreen() {
const router = useRouter();
const handleLogin = async () => {
await login();
// Navigate and reset stack
router.replace('/(app)/home');
// Or push with params
// router.push('/movie/456');
// Or go back
// router.back();
};
return <Pressable onPress={handleLogin}><Text>Login</Text></Pressable>;
}Tab Navigation
// app/(app)/_layout.tsx
import { Tabs } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
export default function TabLayout() {
return (
<Tabs
screenOptions={{
headerShown: false,
tabBarActiveTintColor: '#3b82f6',
tabBarInactiveTintColor: '#9ca3af',
tabBarStyle: { backgroundColor: 'white', borderTopWidth: 0, elevation: 8 },
tabBarItemStyle: { paddingVertical: 8 },
}}
>
<Tabs.Screen
name="index"
options={{
title: 'Home',
tabBarIcon: ({ focused, color }) => (
<Ionicons name={focused ? 'home' : 'home-outline'} size={24} color={color} />
),
}}
/>
<Tabs.Screen
name="search"
options={{
title: 'Search',
tabBarIcon: ({ focused, color }) => (
<Ionicons name={focused ? 'search' : 'search-outline'} size={24} color={color} />
),
}}
/>
<Tabs.Screen
name="profile"
options={{
title: 'Profile',
tabBarIcon: ({ focused, color }) => (
<Ionicons name={focused ? 'person' : 'person-outline'} size={24} color={color} />
),
}}
/>
</Tabs>
);
}Tab Bar Customization
// app/(app)/_layout.tsx - Custom tab bar
import { Tabs, TabBar } from 'expo-router';
import { View, Text, Pressable, StyleSheet } from 'react-native';
function CustomTabBar({ state, descriptors, navigation }) {
return (
<View style={styles.tabBar}>
{state.routes.map((route, index) => {
const { options } = descriptors[route.key];
const label = options.title ?? route.name;
const isFocused = state.index === index;
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
canPreventDefault: true,
});
if (!event.defaultPrevented) {
navigation.navigate(route.name);
}
};
const onLongPress = () => {
navigation.emit({
type: 'tabLongPress',
target: route.key,
});
};
return (
<Pressable
key={route.key}
onPress={onPress}
onLongPress={onLongPress}
style={[styles.tabItem, isFocused && styles.tabItemActive]}
accessibilityRole="tab"
accessibilityState={{ selected: isFocused }}
>
<Text style={[styles.tabLabel, isFocused && styles.tabLabelActive]}>
{label}
</Text>
</Pressable>
);
})}
</View>
);
}
export default function TabLayout() {
return (
<Tabs tabBar={CustomTabBar}>
<Tabs.Screen name="index" options={{ title: 'Home' }} />
<Tabs.Screen name="search" options={{ title: 'Search' }} />
<Tabs.Screen name="profile" options={{ title: 'Profile' }} />
</Tabs>
);
}Route Groups
Route groups ((name)) organize routes without adding to the URL path.
app/
├── (auth)/ # No URL segment
│ ├── _layout.tsx # Stack for auth
│ ├── login.tsx # /login
│ └── register.tsx # /register
├── (app)/ # No URL segment
│ ├── _layout.tsx # Tabs for main app
│ ├── index.tsx # / (home tab)
│ └── profile.tsx # /profile
├── _layout.tsx # Root: chooses (auth) or (app)
└── index.tsx # Redirects to (auth) or (app)
Root Layout with Groups
// app/_layout.tsx
import { Stack } from 'expo-router';
import { useAuth } from '@/hooks/useAuth';
export default function RootLayout() {
const { user, loading } = useAuth();
if (loading) return <SplashScreen />;
return (
<Stack screenOptions={{ headerShown: false }}>
{user ? (
// Authenticated: show app tabs
<Stack.Screen name="(app)" />
) : (
// Not authenticated: show auth stack
<Stack.Screen name="(auth)" />
)}
</Stack>
);
}Auth Layout
// app/(auth)/_layout.tsx
import { Stack } from 'expo-router';
export default function AuthLayout() {
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="login" />
<Stack.Screen name="register" />
<Stack.Screen name="forgot-password" />
</Stack>
);
}App Layout (Tabs)
// app/(app)/_layout.tsx
import { Tabs } from 'expo-router';
export default function AppLayout() {
return (
<Tabs>
<Tabs.Screen name="index" options={{ title: 'Home' }} />
<Tabs.Screen name="search" options={{ title: 'Search' }} />
<Tabs.Screen name="profile" options={{ title: 'Profile' }} />
</Tabs>
);
}Dynamic Routes
// app/movie/[id].tsx
import { useLocalSearchParams } from 'expo-router';
import { View, Text, StyleSheet } from 'react-native';
export default function MovieDetailScreen() {
// Type-safe params
const { id } = useLocalSearchParams<{ id: string }>();
return (
<View style={styles.container}>
<Text style={styles.title}>Movie Detail</Text>
<Text>ID: {id}</Text>
</View>
);
}
// Multiple params: app/user/[userId]/post/[postId].tsx
// const { userId, postId } = useLocalSearchParams<{ userId: string; postId: string }>();Optional Params
// app/search/[query?].tsx - optional query param
const { query } = useLocalSearchParams<{ query?: string }>();
// query is string | undefinedStrict Params (TypeScript)
// app/movie/[id].tsx
import { useLocalSearchParams } from 'expo-router';
// Define param types
type MovieParams = { id: string };
export default function MovieDetailScreen() {
const { id } = useLocalSearchParams<MovieParams>();
// id is typed as string
// TypeScript error if you access non-existent param
}Nested Navigation
// app/(app)/profile/_layout.tsx
import { Stack } from 'expo-router';
export default function ProfileStackLayout() {
return (
<Stack>
<Stack.Screen name="index" options={{ title: 'Profile' }} />
<Stack.Screen name="edit" options={{ title: 'Edit Profile' }} />
<Stack.Screen name="settings" options={{ title: 'Settings' }} />
</Stack>
);
}
// Navigating from tab screen
// router.push('/profile/edit') - pushes onto profile stack
// router.push('/settings') - pushes onto root stack (if settings not in profile)Deep Linking
// app/_layout.tsx
import { Stack } from 'expo-router';
import { Linking } from 'expo-router';
export default function RootLayout() {
return (
<Stack>
<Stack.Screen name="index" />
<Stack.Screen name="movie/[id]" />
<Stack.Screen name="(app)" />
<Stack.Screen name="(auth)" />
</Stack>
);
}
// app.json - configure scheme
{
"expo": {
"scheme": "myapp",
"ios": {
"associatedDomains": ["applinks:myapp.com"]
},
"android": {
"intentFilters": [
{
"action": "VIEW",
"autoVerify": true,
"data": [{ "scheme": "https", "host": "myapp.com" }],
"category": ["BROWSABLE", "DEFAULT"]
}
]
}
}
}Handling Deep Links
// In any screen
import { useEffect } from 'react';
import { Linking } from 'react-native';
import { useRouter } from 'expo-router';
export function MovieDetailScreen() {
const router = useRouter();
const { id } = useLocalSearchParams<{ id: string }>();
useEffect(() => {
const subscription = Linking.addEventListener('url', ({ url }) => {
// Handle incoming deep links
console.log('Deep link:', url);
// myapp://movie/123 -> navigate to /movie/123
});
return () => subscription.remove();
}, []);
return <View><Text>Movie {id}</Text></View>;
}Navigation Options
// Per-screen options
<Tabs.Screen
name="profile"
options={{
title: 'Profile',
tabBarBadge: 3, // Badge count
tabBarBadgeStyle: { backgroundColor: 'red' },
tabBarIcon: ({ focused, color, size }) => (
<Ionicons name={focused ? 'person' : 'person-outline'} size={size} color={color} />
),
// Header options (for Stack)
headerTitle: 'Profile',
headerRight: () => <Button title="Edit" onPress={() => {}} />,
headerStyle: { backgroundColor: '#3b82f6' },
headerTintColor: 'white',
}}
/>Dynamic Options with Hooks
import { useRoute } from 'expo-router';
export function ProfileScreen() {
const route = useRoute();
// route.params contains params
// route.name is the route name
return <View>...</View>;
}
// Or in layout
export default function ProfileLayout() {
return (
<Stack>
<Stack.Screen
name="index"
options={({ route }) => ({
title: route.params?.userName ?? 'Profile',
})}
/>
</Stack>
);
}Navigation Patterns
Modal Presentation
// app/modal.tsx
import { Stack } from 'expo-router';
export default function ModalLayout() {
return (
<Stack screenOptions={{ presentation: 'modal' }}>
<Stack.Screen name="index" />
<Stack.Screen name="confirm" />
</Stack>
);
}
// Navigate: router.push('/modal') - presents as modal
// Dismiss: router.dismiss() or router.back()Replace vs Push
const router = useRouter();
// Push: adds to stack, back button works
router.push('/details');
// Replace: replaces current, no back to previous
router.replace('/home');
// Back: go back one screen
router.back();
// Back to specific route
router.backTo('/home');
// Dismiss all modals
router.dismissAll();
// Reset to route (clear stack)
router.replace('/(app)/home');Navigation Guards
// app/(app)/_layout.tsx
import { Stack, useNavigation } from 'expo-router';
import { useEffect } from 'react';
import { useAuth } from '@/hooks/useAuth';
export default function ProtectedLayout() {
const { user, loading } = useAuth();
const navigation = useNavigation();
useEffect(() => {
if (!loading && !user) {
navigation.replace('/(auth)/login');
}
}, [user, loading]);
if (loading) return <SplashScreen />;
if (!user) return null;
return (
<Tabs>
<Tabs.Screen name="index" />
<Tabs.Screen name="profile" />
</Tabs>
);
}TypeScript with Expo Router
// app/_layout.tsx
import { Stack } from 'expo-router';
// Define route types
declare global {
namespace ExpoRouter {
interface ExpoRouterRoutes {
'/': undefined;
'/about': undefined;
'/movie/[id]': { id: string };
'/user/[userId]/post/[postId]': { userId: string; postId: string };
'/search/[query?]': { query?: string };
'/(auth)/login': undefined;
'/(auth)/register': undefined;
'/(app)': undefined;
'/(app)/profile': undefined;
'/(app)/profile/edit': undefined;
}
}
}Now Link href and router.push are type-checked!
// ✅ Valid
<Link href="/movie/123" />
router.push('/movie/456');
// ❌ TypeScript error - missing param
<Link href="/movie" />
router.push('/movie');
// ❌ TypeScript error - wrong param name
<Link href="/movie/123?foo=bar" />Try It
Create (app) with 3 tabs. Add a nested stack to profile tab with edit/settings screens. Test navigation.
# Create the structure
mkdir -p app/\(app\)/profile
touch app/\(app\)/_layout.tsx
touch app/\(app\)/index.tsx
touch app/\(app\)/search.tsx
touch app/\(app\)/profile.tsx
touch app/\(app\)/profile/_layout.tsx
touch app/\(app\)/profile/edit.tsx
touch app/\(app\)/profile/settings.tsxImplement deep linking
- Configure app scheme in app.json
- Set up Associated Domains (iOS) / Intent Filters (Android)
- Test:
npx uri-scheme open myapp://movie/123 --ios - Test:
npx uri-scheme open myapp://movie/123 --android - Handle the deep link in MovieDetailScreen
- Verify it works from cold start and background
Expo Router maps files to routes. Use (group) for layouts without URL segments. Stack for hierarchical, Tabs for peer screens. Dynamic routes with [param]. TypeScript catches missing params. Deep linking requires scheme + associated domains/intent filters.
Resources
- Expo Router Introduction: https://docs.expo.dev/router/introduction/
- Expo Router: Route Groups: https://docs.expo.dev/router/advanced/route-groups/
- Expo Router: Navigation Patterns: https://docs.expo.dev/router/advanced/navigation-patterns/
- Expo Router: TypeScript: https://docs.expo.dev/router/reference/typescript/