0
# Containers and Contexts
1
2
Navigation container and context components that manage navigation state, distribute it throughout the app component tree, and provide theming and lifecycle management.
3
4
## Capabilities
5
6
### BaseNavigationContainer
7
8
Container component that holds the navigation state and should be rendered at the root of the app, wrapping all navigators and screens.
9
10
```typescript { .api }
11
/**
12
* Root navigation container that manages navigation state
13
* @param props - Navigation container configuration
14
* @returns Navigation container component
15
*/
16
function BaseNavigationContainer(props: NavigationContainerProps): React.JSX.Element;
17
18
interface NavigationContainerProps {
19
/** Initial navigation state for deep linking or state restoration */
20
initialState?: InitialState;
21
/** Callback invoked when navigation state changes */
22
onStateChange?: (state: NavigationState | undefined) => void;
23
/** Callback invoked when navigation tree mounts and is ready */
24
onReady?: () => void;
25
/** Callback invoked when navigation action is not handled */
26
onUnhandledAction?: (action: NavigationAction) => void;
27
/** Theme object for UI styling */
28
theme?: ReactNavigation.Theme;
29
/** Child navigator components and screens */
30
children: React.ReactNode;
31
}
32
33
type InitialState = Partial<NavigationState> | {
34
routes: { name: string; params?: object; state?: InitialState }[];
35
};
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
import React from 'react';
42
import { BaseNavigationContainer } from "@react-navigation/core";
43
44
// Basic setup
45
function App() {
46
return (
47
<BaseNavigationContainer>
48
<RootNavigator />
49
</BaseNavigationContainer>
50
);
51
}
52
53
// With state persistence and callbacks
54
function AppWithPersistence() {
55
const [initialState, setInitialState] = useState();
56
const [isReady, setIsReady] = useState(false);
57
58
useEffect(() => {
59
const restoreState = async () => {
60
try {
61
const savedState = await AsyncStorage.getItem('navigation_state');
62
if (savedState) {
63
setInitialState(JSON.parse(savedState));
64
}
65
} finally {
66
setIsReady(true);
67
}
68
};
69
70
restoreState();
71
}, []);
72
73
if (!isReady) {
74
return <SplashScreen />;
75
}
76
77
return (
78
<BaseNavigationContainer
79
initialState={initialState}
80
onStateChange={(state) => {
81
AsyncStorage.setItem('navigation_state', JSON.stringify(state));
82
}}
83
onReady={() => {
84
console.log('Navigation ready');
85
}}
86
theme={isDark ? darkTheme : lightTheme}
87
>
88
<RootNavigator />
89
</BaseNavigationContainer>
90
);
91
}
92
```
93
94
### NavigationContainerRef
95
96
Reference object for imperative navigation access outside of component tree.
97
98
```typescript { .api }
99
/**
100
* Create a navigation container ref for imperative access
101
* @returns Ref object with navigation methods
102
*/
103
function createNavigationContainerRef<ParamList extends ParamListBase = ParamListBase>():
104
NavigationContainerRefWithCurrent<ParamList>;
105
106
interface NavigationContainerRef<ParamList extends ParamListBase = ParamListBase> {
107
/** Navigate to a screen */
108
navigate<RouteName extends keyof ParamList>(
109
name: RouteName,
110
params?: ParamList[RouteName]
111
): void;
112
/** Go back to previous screen */
113
goBack(): void;
114
/** Dispatch navigation action */
115
dispatch(action: NavigationAction): void;
116
/** Reset navigation state to provided state */
117
resetRoot(state?: PartialState<NavigationState> | NavigationState): void;
118
/** Get the current navigation state */
119
getRootState(): NavigationState;
120
/** Get the currently focused route */
121
getCurrentRoute(): Route<string> | undefined;
122
/** Get current screen options */
123
getCurrentOptions(): object | undefined;
124
/** Check if navigation is ready to handle actions */
125
isReady(): boolean;
126
/** Add event listener */
127
addListener<EventName extends keyof NavigationContainerEventMap>(
128
type: EventName,
129
callback: (e: NavigationContainerEventMap[EventName]) => void
130
): () => void;
131
}
132
133
interface NavigationContainerRefWithCurrent<ParamList extends ParamListBase = ParamListBase>
134
extends NavigationContainerRef<ParamList> {
135
current: NavigationContainerRef<ParamList> | null;
136
}
137
```
138
139
**Usage Examples:**
140
141
```typescript
142
import { createNavigationContainerRef } from "@react-navigation/core";
143
144
// Create ref
145
const navigationRef = createNavigationContainerRef();
146
147
function App() {
148
return (
149
<BaseNavigationContainer ref={navigationRef}>
150
<RootNavigator />
151
</BaseNavigationContainer>
152
);
153
}
154
155
// Use ref for imperative navigation
156
function navigateFromOutsideComponent() {
157
if (navigationRef.isReady()) {
158
navigationRef.navigate('Profile', { userId: '123' });
159
}
160
}
161
162
// Listen to navigation events
163
navigationRef.addListener('state', (e) => {
164
console.log('Navigation state changed', e.data.state);
165
});
166
167
// Reset navigation state
168
function resetNavigation() {
169
navigationRef.resetRoot({
170
index: 0,
171
routes: [{ name: 'Home' }],
172
});
173
}
174
```
175
176
### NavigationContext
177
178
React context that provides the navigation prop to child components.
179
180
```typescript { .api }
181
/**
182
* Context that holds navigation prop for a screen
183
*/
184
const NavigationContext: React.Context<NavigationProp<ParamListBase> | undefined>;
185
```
186
187
**Usage Examples:**
188
189
```typescript
190
import { NavigationContext } from "@react-navigation/core";
191
import { useContext } from 'react';
192
193
// Access navigation context directly
194
function MyComponent() {
195
const navigation = useContext(NavigationContext);
196
197
if (!navigation) {
198
throw new Error('NavigationContext not found');
199
}
200
201
return (
202
<Button
203
title="Navigate"
204
onPress={() => navigation.navigate('Profile')}
205
/>
206
);
207
}
208
209
// Provide navigation context manually
210
function CustomProvider({ navigation, children }) {
211
return (
212
<NavigationContext.Provider value={navigation}>
213
{children}
214
</NavigationContext.Provider>
215
);
216
}
217
```
218
219
### NavigationRouteContext
220
221
React context that provides the route prop to child components.
222
223
```typescript { .api }
224
/**
225
* Context that holds route prop for a screen
226
*/
227
const NavigationRouteContext: React.Context<RouteProp<ParamListBase> | undefined>;
228
```
229
230
**Usage Examples:**
231
232
```typescript
233
import { NavigationRouteContext } from "@react-navigation/core";
234
import { useContext } from 'react';
235
236
function MyComponent() {
237
const route = useContext(NavigationRouteContext);
238
239
if (!route) {
240
throw new Error('NavigationRouteContext not found');
241
}
242
243
return (
244
<View>
245
<Text>Current route: {route.name}</Text>
246
<Text>Route key: {route.key}</Text>
247
</View>
248
);
249
}
250
```
251
252
### ThemeProvider
253
254
Provider component for theme context, enabling consistent theming throughout navigation components.
255
256
```typescript { .api }
257
/**
258
* Provider component for theme context
259
* @param props - Theme provider props
260
* @returns Theme provider component
261
*/
262
function ThemeProvider(props: ThemeProviderProps): React.JSX.Element;
263
264
interface ThemeProviderProps {
265
/** Theme object to provide to child components */
266
value: ReactNavigation.Theme;
267
/** Child components that will receive theme */
268
children: React.ReactNode;
269
}
270
271
interface Theme {
272
/** Whether the theme is dark mode */
273
dark: boolean;
274
/** Theme color palette */
275
colors: {
276
/** Primary color for highlights and active states */
277
primary: string;
278
/** Background color for screens */
279
background: string;
280
/** Background color for cards and surfaces */
281
card: string;
282
/** Text color */
283
text: string;
284
/** Border color */
285
border: string;
286
/** Notification color for badges and alerts */
287
notification: string;
288
};
289
}
290
```
291
292
**Usage Examples:**
293
294
```typescript
295
import { ThemeProvider } from "@react-navigation/core";
296
297
const lightTheme = {
298
dark: false,
299
colors: {
300
primary: '#007AFF',
301
background: '#FFFFFF',
302
card: '#F2F2F2',
303
text: '#000000',
304
border: '#E5E5E5',
305
notification: '#FF3B30',
306
},
307
};
308
309
const darkTheme = {
310
dark: true,
311
colors: {
312
primary: '#0A84FF',
313
background: '#000000',
314
card: '#1C1C1E',
315
text: '#FFFFFF',
316
border: '#38383A',
317
notification: '#FF453A',
318
},
319
};
320
321
function App() {
322
const [isDark, setIsDark] = useState(false);
323
324
return (
325
<ThemeProvider value={isDark ? darkTheme : lightTheme}>
326
<BaseNavigationContainer>
327
<RootNavigator />
328
</BaseNavigationContainer>
329
</ThemeProvider>
330
);
331
}
332
333
// Accessing theme in components
334
function ThemedButton({ title, onPress }) {
335
const theme = useTheme();
336
337
return (
338
<TouchableOpacity
339
style={{
340
backgroundColor: theme.colors.primary,
341
padding: 12,
342
borderRadius: 8,
343
}}
344
onPress={onPress}
345
>
346
<Text style={{ color: theme.colors.background }}>
347
{title}
348
</Text>
349
</TouchableOpacity>
350
);
351
}
352
```
353
354
### PreventRemoveProvider
355
356
Provider for prevent remove context, enabling prevention of navigation under certain conditions.
357
358
```typescript { .api }
359
/**
360
* Provider for prevent remove functionality
361
* @param props - Prevent remove provider props
362
* @returns Prevent remove provider component
363
*/
364
function PreventRemoveProvider(props: PreventRemoveProviderProps): React.JSX.Element;
365
366
interface PreventRemoveProviderProps {
367
/** Child components */
368
children: React.ReactNode;
369
}
370
```
371
372
**Usage Examples:**
373
374
```typescript
375
import { PreventRemoveProvider, usePreventRemove } from "@react-navigation/core";
376
377
function FormScreen() {
378
const [hasChanges, setHasChanges] = useState(false);
379
380
return (
381
<PreventRemoveProvider>
382
<FormWithPreventRemove
383
hasChanges={hasChanges}
384
onChangesMade={() => setHasChanges(true)}
385
onChangesSaved={() => setHasChanges(false)}
386
/>
387
</PreventRemoveProvider>
388
);
389
}
390
391
function FormWithPreventRemove({ hasChanges, onChangesMade, onChangesSaved }) {
392
usePreventRemove(hasChanges, ({ data }) => {
393
Alert.alert(
394
'Unsaved Changes',
395
'You have unsaved changes. Are you sure you want to leave?',
396
[
397
{ text: 'Stay', style: 'cancel' },
398
{ text: 'Leave', onPress: () => navigation.dispatch(data.action) }
399
]
400
);
401
});
402
403
return (
404
<View>
405
<TextInput onChangeText={onChangesMade} />
406
<Button title="Save" onPress={onChangesSaved} />
407
</View>
408
);
409
}
410
```
411
412
### NavigationIndependentTree
413
414
Component to create independent navigation trees that don't interfere with the main navigation hierarchy.
415
416
```typescript { .api }
417
/**
418
* Component to create independent navigation trees
419
* @param props - Independent tree props
420
* @returns Independent navigation tree component
421
*/
422
function NavigationIndependentTree(props: NavigationIndependentTreeProps): React.JSX.Element;
423
424
interface NavigationIndependentTreeProps {
425
/** Child components forming the independent tree */
426
children: React.ReactNode;
427
}
428
```
429
430
**Usage Examples:**
431
432
```typescript
433
import { NavigationIndependentTree } from "@react-navigation/core";
434
435
function App() {
436
return (
437
<BaseNavigationContainer>
438
<MainNavigator />
439
440
{/* Independent navigation tree for modals */}
441
<NavigationIndependentTree>
442
<ModalNavigator />
443
</NavigationIndependentTree>
444
</BaseNavigationContainer>
445
);
446
}
447
448
// Use case: Modal with its own navigation
449
function ModalWithNavigation() {
450
return (
451
<NavigationIndependentTree>
452
<ModalStack.Navigator>
453
<ModalStack.Screen name="ModalHome" component={ModalHome} />
454
<ModalStack.Screen name="ModalSettings" component={ModalSettings} />
455
</ModalStack.Navigator>
456
</NavigationIndependentTree>
457
);
458
}
459
```
460
461
### Additional Context Components
462
463
Other context components for specialized navigation functionality.
464
465
```typescript { .api }
466
/**
467
* Context for navigation container reference
468
*/
469
const NavigationContainerRefContext: React.Context<NavigationContainerRef<any> | undefined>;
470
471
/**
472
* Context for navigation helpers
473
*/
474
const NavigationHelpersContext: React.Context<NavigationHelpers<any> | undefined>;
475
476
/**
477
* Context for current render state (internal)
478
*/
479
const CurrentRenderContext: React.Context<any>;
480
481
/**
482
* Context for prevent remove functionality
483
*/
484
const PreventRemoveContext: React.Context<{
485
preventedRoutes: Record<string, { routeKey: string; callback: Function }>;
486
addPreventRemove: (routeKey: string, callback: Function) => void;
487
removePreventRemove: (routeKey: string) => void;
488
} | undefined>;
489
```
490
491
These contexts are typically used internally by the navigation system or for advanced custom navigator implementations.