0
# Static Navigation
1
2
Static navigation enables type-safe navigation configuration by generating navigation components from static definitions. This approach provides compile-time type checking and automatic deep linking path generation.
3
4
## Capabilities
5
6
### createStaticNavigation Function
7
8
Creates a navigation component from a static navigation configuration tree.
9
10
```typescript { .api }
11
/**
12
* Create a navigation component from a static navigation config.
13
* The returned component is a wrapper around NavigationContainer.
14
*/
15
function createStaticNavigation(
16
tree: StaticNavigation<any, any, any>
17
): React.ForwardRefExoticComponent<
18
StaticNavigationProps & React.RefAttributes<NavigationContainerRef<ParamListBase>>
19
>;
20
21
type StaticNavigationProps = Omit<
22
React.ComponentProps<typeof NavigationContainer>,
23
'linking' | 'children'
24
> & {
25
/** Options for deep linking */
26
linking?: Omit<LinkingOptions<ParamListBase>, 'config' | 'enabled'> & {
27
/** Whether deep link handling should be enabled. 'auto' generates paths automatically */
28
enabled?: 'auto' | true | false;
29
/** Additional configuration excluding screens (auto-generated from tree) */
30
config?: Omit<NonNullable<LinkingOptions<ParamListBase>['config']>, 'screens'>;
31
};
32
};
33
```
34
35
**Usage Examples:**
36
37
```typescript
38
import { createStaticNavigation } from '@react-navigation/native';
39
import { createStackNavigator } from '@react-navigation/stack';
40
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
41
42
// Define screen components
43
function HomeScreen() {
44
return <Text>Home Screen</Text>;
45
}
46
47
function ProfileScreen() {
48
return <Text>Profile Screen</Text>;
49
}
50
51
function SettingsScreen() {
52
return <Text>Settings Screen</Text>;
53
}
54
55
// Create static navigator configurations
56
const HomeStack = createStackNavigator({
57
screens: {
58
Home: HomeScreen,
59
Profile: ProfileScreen,
60
},
61
});
62
63
const SettingsStack = createStackNavigator({
64
screens: {
65
Settings: SettingsScreen,
66
},
67
});
68
69
// Create root tab navigator
70
const RootTabs = createBottomTabNavigator({
71
screens: {
72
HomeTab: HomeStack,
73
SettingsTab: SettingsStack,
74
},
75
});
76
77
// Generate the navigation component
78
const Navigation = createStaticNavigation(RootTabs);
79
80
// Use in your app
81
function App() {
82
return <Navigation />;
83
}
84
```
85
86
### Static Navigation Configuration
87
88
Define navigation structure using static configuration objects with full type safety.
89
90
```typescript { .api }
91
// StaticNavigation types are provided by individual navigator packages
92
interface StaticNavigation<
93
ScreenOptions,
94
NavigatorOptions,
95
EventMap
96
> {
97
screens: Record<string, StaticNavigation<any, any, any> | React.ComponentType>;
98
navigatorOptions?: NavigatorOptions;
99
screenOptions?: ScreenOptions | ((props: any) => ScreenOptions);
100
}
101
```
102
103
**Configuration Examples:**
104
105
```typescript
106
// Simple stack configuration
107
const SimpleStack = createStackNavigator({
108
screens: {
109
Home: HomeScreen,
110
Details: DetailsScreen,
111
},
112
});
113
114
// Stack with screen options
115
const StyledStack = createStackNavigator({
116
screens: {
117
Home: {
118
screen: HomeScreen,
119
options: {
120
title: 'Welcome',
121
headerStyle: { backgroundColor: '#007AFF' },
122
},
123
},
124
Profile: {
125
screen: ProfileScreen,
126
options: ({ route }) => ({
127
title: route.params?.name || 'Profile',
128
}),
129
},
130
},
131
screenOptions: {
132
headerTintColor: '#fff',
133
},
134
});
135
136
// Nested navigator configuration
137
const RootNavigator = createStackNavigator({
138
screens: {
139
Auth: createStackNavigator({
140
screens: {
141
Login: LoginScreen,
142
Register: RegisterScreen,
143
},
144
screenOptions: {
145
headerShown: false,
146
},
147
}),
148
Main: createBottomTabNavigator({
149
screens: {
150
Home: HomeStack,
151
Profile: ProfileStack,
152
Settings: SettingsScreen,
153
},
154
}),
155
},
156
});
157
158
// Complex nested structure
159
const AppNavigator = createStackNavigator({
160
screens: {
161
Onboarding: OnboardingScreen,
162
Main: createBottomTabNavigator({
163
screens: {
164
Feed: createStackNavigator({
165
screens: {
166
FeedList: FeedListScreen,
167
Post: PostScreen,
168
Comments: CommentsScreen,
169
},
170
}),
171
Search: createStackNavigator({
172
screens: {
173
SearchHome: SearchHomeScreen,
174
SearchResults: SearchResultsScreen,
175
SearchFilters: SearchFiltersScreen,
176
},
177
}),
178
Profile: createStackNavigator({
179
screens: {
180
ProfileHome: ProfileHomeScreen,
181
ProfileEdit: ProfileEditScreen,
182
ProfileSettings: ProfileSettingsScreen,
183
},
184
}),
185
},
186
}),
187
},
188
});
189
```
190
191
### Automatic Deep Linking
192
193
Static navigation can automatically generate deep linking paths based on the navigation structure.
194
195
```typescript { .api }
196
// Linking configuration for static navigation
197
interface StaticLinkingConfig {
198
/** Whether to enable automatic path generation */
199
enabled?: 'auto' | true | false;
200
/** URL prefixes to handle */
201
prefixes?: string[];
202
/** Additional configuration excluding auto-generated screens */
203
config?: {
204
path?: string;
205
initialRouteName?: string;
206
};
207
}
208
```
209
210
**Deep Linking Examples:**
211
212
```typescript
213
// Automatic path generation
214
const Navigation = createStaticNavigation(RootNavigator);
215
216
function App() {
217
return (
218
<Navigation
219
linking={{
220
enabled: 'auto', // Generates paths automatically
221
prefixes: ['myapp://'],
222
}}
223
/>
224
);
225
}
226
227
// Generated paths would be:
228
// myapp://onboarding -> Onboarding screen
229
// myapp://main/feed/feed-list -> FeedList screen
230
// myapp://main/feed/post -> Post screen
231
// myapp://main/search/search-home -> SearchHome screen
232
// myapp://main/profile/profile-home -> ProfileHome screen
233
234
// Manual path configuration
235
function AppWithCustomPaths() {
236
return (
237
<Navigation
238
linking={{
239
enabled: true,
240
prefixes: ['myapp://'],
241
config: {
242
initialRouteName: 'Main',
243
},
244
// Custom path mappings override auto-generated ones
245
screens: {
246
Main: {
247
screens: {
248
Feed: {
249
screens: {
250
FeedList: 'home',
251
Post: 'post/:id',
252
},
253
},
254
Profile: {
255
screens: {
256
ProfileHome: 'profile',
257
ProfileEdit: 'profile/edit',
258
},
259
},
260
},
261
},
262
},
263
}}
264
/>
265
);
266
}
267
268
// Disable linking entirely
269
function AppWithoutLinking() {
270
return (
271
<Navigation
272
linking={{
273
enabled: false,
274
}}
275
/>
276
);
277
}
278
```
279
280
### Type Safety
281
282
Static navigation provides compile-time type checking for navigation operations.
283
284
```typescript { .api }
285
// Type-safe navigation with static configuration
286
declare global {
287
namespace ReactNavigation {
288
interface RootParamList {
289
Home: undefined;
290
Profile: { userId: string };
291
Settings: undefined;
292
Post: { id: number; slug?: string };
293
}
294
}
295
}
296
```
297
298
**Type Safety Examples:**
299
300
```typescript
301
// Navigation component with full type safety
302
const TypedNavigation = createStaticNavigation(
303
createStackNavigator({
304
screens: {
305
Home: HomeScreen,
306
Profile: ProfileScreen, // Expects { userId: string }
307
Post: PostScreen, // Expects { id: number; slug?: string }
308
},
309
})
310
);
311
312
// Type-safe navigation in components
313
function HomeScreen() {
314
const navigation = useNavigation();
315
316
const goToProfile = () => {
317
// ✅ TypeScript ensures correct params
318
navigation.navigate('Profile', { userId: '123' });
319
};
320
321
const goToPost = () => {
322
// ✅ Optional params work correctly
323
navigation.navigate('Post', { id: 1, slug: 'my-post' });
324
};
325
326
const invalidNavigation = () => {
327
// ❌ TypeScript error - missing required userId
328
navigation.navigate('Profile');
329
330
// ❌ TypeScript error - wrong param type
331
navigation.navigate('Post', { id: '123' });
332
};
333
334
return (
335
<View>
336
<Button title="Go to Profile" onPress={goToProfile} />
337
<Button title="Go to Post" onPress={goToPost} />
338
</View>
339
);
340
}
341
342
// Type-safe links
343
function TypedLinks() {
344
return (
345
<View>
346
{/* ✅ Correct typing */}
347
<Link screen="Profile" params={{ userId: '123' }}>
348
Profile
349
</Link>
350
351
{/* ❌ TypeScript error - missing required param */}
352
<Link screen="Profile">
353
Profile
354
</Link>
355
</View>
356
);
357
}
358
```
359
360
### Navigation Ref Integration
361
362
Static navigation components support ref forwarding for programmatic navigation.
363
364
```typescript { .api }
365
// Ref type for static navigation
366
type StaticNavigationRef = NavigationContainerRef<ParamListBase>;
367
```
368
369
**Ref Usage Examples:**
370
371
```typescript
372
import { useRef } from 'react';
373
import type { NavigationContainerRef } from '@react-navigation/native';
374
375
function App() {
376
const navigationRef = useRef<NavigationContainerRef<RootParamList>>(null);
377
378
const handleDeepLink = (url: string) => {
379
// Parse URL and navigate programmatically
380
if (url.includes('/profile/')) {
381
const userId = extractUserId(url);
382
navigationRef.current?.navigate('Profile', { userId });
383
}
384
};
385
386
return (
387
<Navigation
388
ref={navigationRef}
389
onReady={() => {
390
console.log('Navigation ready');
391
// Can safely use navigationRef.current here
392
}}
393
onStateChange={(state) => {
394
console.log('Navigation state changed:', state);
395
}}
396
/>
397
);
398
}
399
400
// Using navigation ref with external libraries
401
function AppWithAnalytics() {
402
const navigationRef = useRef<NavigationContainerRef<RootParamList>>(null);
403
404
return (
405
<Navigation
406
ref={navigationRef}
407
onStateChange={(state) => {
408
const currentRoute = navigationRef.current?.getCurrentRoute();
409
if (currentRoute) {
410
analytics.track('Screen View', {
411
screen: currentRoute.name,
412
params: currentRoute.params,
413
});
414
}
415
}}
416
/>
417
);
418
}
419
```
420
421
### Integration with Navigator Libraries
422
423
Static navigation works with all React Navigation navigator libraries.
424
425
```typescript { .api }
426
// Compatible navigator types
427
interface CompatibleNavigators {
428
'@react-navigation/stack': typeof createStackNavigator;
429
'@react-navigation/bottom-tabs': typeof createBottomTabNavigator;
430
'@react-navigation/material-top-tabs': typeof createMaterialTopTabNavigator;
431
'@react-navigation/drawer': typeof createDrawerNavigator;
432
'@react-navigation/native-stack': typeof createNativeStackNavigator;
433
}
434
```
435
436
**Multi-Navigator Examples:**
437
438
```typescript
439
import { createStackNavigator } from '@react-navigation/stack';
440
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
441
import { createDrawerNavigator } from '@react-navigation/drawer';
442
443
// Complex navigation structure using multiple navigator types
444
const AppNavigator = createDrawerNavigator({
445
screens: {
446
Main: createBottomTabNavigator({
447
screens: {
448
Home: createStackNavigator({
449
screens: {
450
HomeList: HomeListScreen,
451
HomeDetail: HomeDetailScreen,
452
},
453
}),
454
Search: createStackNavigator({
455
screens: {
456
SearchHome: SearchHomeScreen,
457
SearchResults: SearchResultsScreen,
458
},
459
}),
460
Profile: ProfileScreen,
461
},
462
}),
463
Settings: SettingsScreen,
464
Help: HelpScreen,
465
},
466
});
467
468
const Navigation = createStaticNavigation(AppNavigator);
469
470
function App() {
471
return (
472
<Navigation
473
linking={{
474
enabled: 'auto',
475
prefixes: ['myapp://'],
476
}}
477
/>
478
);
479
}
480
```