Using Expo Router for Navigation in React Native
Introduction
Expo Router brings file-based routing to React Native, mimicking Next.js’s approach. This guide covers project setup, defining routes, dynamic segments, and nested layouts.
Prerequisites
- Node.js >=16
- Expo CLI
- Basic React Native knowledge
Step 1: Initialize Expo Project
npx create-expo-app expo-router-app
cd expo-router-app
Step 2: Install Expo Router
npm install expo-router react-native-safe-area-context react-native-screens
Step 3: Configure Babel
Add plugin in babel.config.js
:
module.exports = function (api) {
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: ["expo-router/babel"],
};
};
Step 4: Create App Entry
Replace App.js
with entry.js
:
import "expo-router/entry";
Step 5: Define Routes Folder
Create app
directory:
app/
├── _layout.js
├── index.js
├── about.js
└── users/[id].js
- _layout.js: Wraps all screens
- index.js: Home screen
- about.js: About screen
- users/[id].js: Dynamic user profile
Example app/_layout.js
import { Stack } from "expo-router";
export default function Layout() {
return <Stack />;
}
Example app/index.js
import { Link } from "expo-router";
import { Text, View, Button } from "react-native";
export default function Home() {
return (
<View className="flex-1 items-center justify-center">
<Text>Home Screen</Text>
<Link href="/about" asChild>
<Button title="Go to About" />
</Link>
</View>
);
}
Step 6: Dynamic Route Example
app/users/[id].js
:
import { useRouter, useSearchParams } from "expo-router";
import { Text, View } from "react-native";
export default function UserProfile() {
const { back } = useRouter();
const { id } = useSearchParams();
return (
<View className="flex-1 items-center justify-center">
<Text>User Profile: {id}</Text>
<Button title="Go Back" onPress={() => back()} />
</View>
);
}
Step 7: Nested Layouts
Create nested folder app/dashboard/settings.js
and layout app/dashboard/_layout.js
.
Summary
Expo Router simplifies React Native navigation with file-based routing, dynamic routes, and layouts. It enhances developer experience and aligns RN routing with web paradigms.