0
# Navigation Props and Hooks
1
2
Navigation properties, screen props, event handling, and utility hooks for accessing navigation state and header information in native stack navigators.
3
4
## Capabilities
5
6
### Screen Props
7
8
Props provided to screen components with navigation and route information.
9
10
```typescript { .api }
11
/**
12
* Props provided to each screen component
13
*/
14
type NativeStackScreenProps<
15
ParamList extends ParamListBase,
16
RouteName extends keyof ParamList = string,
17
NavigatorID extends string | undefined = undefined
18
> = {
19
navigation: NativeStackNavigationProp<ParamList, RouteName, NavigatorID>;
20
route: RouteProp<ParamList, RouteName>;
21
};
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import { NativeStackScreenProps } from "@react-navigation/native-stack";
28
29
type RootStackParamList = {
30
Profile: { userId: string };
31
Settings: undefined;
32
};
33
34
type ProfileScreenProps = NativeStackScreenProps<RootStackParamList, 'Profile'>;
35
36
function ProfileScreen({ navigation, route }: ProfileScreenProps) {
37
const { userId } = route.params;
38
39
return (
40
<View>
41
<Text>User ID: {userId}</Text>
42
<Button
43
title="Go to Settings"
44
onPress={() => navigation.navigate('Settings')}
45
/>
46
</View>
47
);
48
}
49
```
50
51
### Navigation Prop
52
53
The navigation prop provides methods for navigating between screens and stack manipulation.
54
55
```typescript { .api }
56
/**
57
* Navigation prop with native stack-specific methods
58
*/
59
type NativeStackNavigationProp<
60
ParamList extends ParamListBase,
61
RouteName extends keyof ParamList = string,
62
NavigatorID extends string | undefined = undefined
63
> = NavigationProp<
64
ParamList,
65
RouteName,
66
NavigatorID,
67
StackNavigationState<ParamList>,
68
NativeStackNavigationOptions,
69
NativeStackNavigationEventMap
70
> & StackActionHelpers<ParamList>;
71
72
/**
73
* Core navigation methods available on navigation prop
74
*/
75
interface NavigationMethods<ParamList extends ParamListBase> {
76
navigate<RouteName extends keyof ParamList>(
77
name: RouteName,
78
params?: ParamList[RouteName]
79
): void;
80
push<RouteName extends keyof ParamList>(
81
name: RouteName,
82
params?: ParamList[RouteName]
83
): void;
84
pop(count?: number): void;
85
popToTop(): void;
86
goBack(): void;
87
canGoBack(): boolean;
88
replace<RouteName extends keyof ParamList>(
89
name: RouteName,
90
params?: ParamList[RouteName]
91
): void;
92
setOptions(options: Partial<NativeStackNavigationOptions>): void;
93
setParams(params: Partial<ParamList[RouteName]>): void;
94
addListener(type: string, callback: Function): Function;
95
removeListener(type: string, callback: Function): void;
96
isFocused(): boolean;
97
}
98
```
99
100
**Navigation Methods Examples:**
101
102
```typescript
103
function HomeScreen({ navigation }: NativeStackScreenProps<RootStackParamList, 'Home'>) {
104
const handleNavigation = () => {
105
// Navigate to a screen
106
navigation.navigate('Profile', { userId: '123' });
107
108
// Push a new screen (allows multiple instances)
109
navigation.push('Details', { itemId: 456 });
110
111
// Go back
112
navigation.goBack();
113
114
// Pop to root
115
navigation.popToTop();
116
117
// Replace current screen
118
navigation.replace('Login');
119
120
// Update screen options dynamically
121
navigation.setOptions({
122
title: 'Updated Title',
123
headerRight: () => <Button title="Save" onPress={save} />,
124
});
125
};
126
127
return (
128
// Screen content
129
);
130
}
131
```
132
133
### Navigation Events
134
135
Event system for responding to navigation state changes and transitions.
136
137
```typescript { .api }
138
/**
139
* Native stack-specific navigation events
140
*/
141
interface NativeStackNavigationEventMap {
142
/**
143
* Event fired when a transition animation starts
144
*/
145
transitionStart: { data: { closing: boolean } };
146
/**
147
* Event fired when a transition animation ends
148
*/
149
transitionEnd: { data: { closing: boolean } };
150
/**
151
* Event fired when a swipe back gesture is cancelled on iOS
152
*/
153
gestureCancel: { data: undefined };
154
/**
155
* Event fired when sheet presentation detent changes
156
*/
157
sheetDetentChange: { data: { index: number; stable: boolean } };
158
}
159
```
160
161
**Event Handling Examples:**
162
163
```typescript
164
function ScreenWithEvents({ navigation }: NativeStackScreenProps<RootStackParamList, 'Home'>) {
165
React.useEffect(() => {
166
// Listen for transition events
167
const unsubscribeTransitionStart = navigation.addListener('transitionStart', (e) => {
168
console.log('Transition started:', e.data.closing ? 'closing' : 'opening');
169
});
170
171
const unsubscribeTransitionEnd = navigation.addListener('transitionEnd', (e) => {
172
console.log('Transition ended:', e.data.closing ? 'closed' : 'opened');
173
});
174
175
// Listen for sheet detent changes
176
const unsubscribeSheetDetent = navigation.addListener('sheetDetentChange', (e) => {
177
console.log('Sheet detent changed to index:', e.data.index, 'stable:', e.data.stable);
178
});
179
180
return () => {
181
unsubscribeTransitionStart();
182
unsubscribeTransitionEnd();
183
unsubscribeSheetDetent();
184
};
185
}, [navigation]);
186
187
return (
188
// Screen content
189
);
190
}
191
```
192
193
### Options Args
194
195
Props provided to dynamic screen options functions.
196
197
```typescript { .api }
198
/**
199
* Arguments provided to screen options functions
200
*/
201
type NativeStackOptionsArgs<
202
ParamList extends ParamListBase,
203
RouteName extends keyof ParamList = keyof ParamList,
204
NavigatorID extends string | undefined = undefined
205
> = NativeStackScreenProps<ParamList, RouteName, NavigatorID> & {
206
theme: Theme;
207
};
208
```
209
210
**Dynamic Options Examples:**
211
212
```typescript
213
<Stack.Screen
214
name="Profile"
215
component={ProfileScreen}
216
options={({ route, navigation, theme }: NativeStackOptionsArgs<RootStackParamList, 'Profile'>) => ({
217
title: route.params?.name || 'Profile',
218
headerStyle: { backgroundColor: theme.colors.primary },
219
headerRight: ({ tintColor }) => (
220
<TouchableOpacity onPress={() => navigation.navigate('EditProfile')}>
221
<Icon name="edit" color={tintColor} />
222
</TouchableOpacity>
223
),
224
})}
225
/>
226
```
227
228
### Animated Header Height Hook
229
230
Hook for accessing animated header height values for custom scroll behaviors.
231
232
```typescript { .api }
233
/**
234
* Hook to get the animated header height value
235
* Must be used within a screen in a native stack navigator
236
* @returns Animated value representing the header height
237
* @throws Error if used outside of native stack navigator context with message:
238
* "Couldn't find the header height. Are you inside a screen in a native stack navigator?"
239
*/
240
function useAnimatedHeaderHeight(): Animated.AnimatedInterpolation<number>;
241
242
/**
243
* Context that provides the animated header height value
244
* Used internally by useAnimatedHeaderHeight hook
245
*/
246
const AnimatedHeaderHeightContext: React.Context<Animated.AnimatedInterpolation<number> | undefined>;
247
```
248
249
**Usage Examples:**
250
251
```typescript
252
import { useAnimatedHeaderHeight } from "@react-navigation/native-stack";
253
import { Animated } from "react-native";
254
255
function ScrollScreen() {
256
const headerHeight = useAnimatedHeaderHeight();
257
const scrollY = new Animated.Value(0);
258
259
// Use header height in animations
260
const headerOpacity = scrollY.interpolate({
261
inputRange: [0, headerHeight],
262
outputRange: [1, 0],
263
extrapolate: 'clamp',
264
});
265
266
return (
267
<Animated.ScrollView
268
contentInsetAdjustmentBehavior="automatic"
269
onScroll={Animated.event(
270
[{ nativeEvent: { contentOffset: { y: scrollY } } }],
271
{ useNativeDriver: false }
272
)}
273
scrollEventThrottle={16}
274
>
275
<Animated.View style={{ opacity: headerOpacity }}>
276
{/* Content that fades based on scroll */}
277
</Animated.View>
278
</Animated.ScrollView>
279
);
280
}
281
```
282
283
### Route Prop
284
285
Route information provided to screen components.
286
287
```typescript { .api }
288
/**
289
* Route prop containing screen parameters and metadata
290
*/
291
interface RouteProp<ParamList extends ParamListBase, RouteName extends keyof ParamList> {
292
key: string;
293
name: RouteName;
294
params: ParamList[RouteName];
295
path?: string;
296
}
297
```
298
299
**Route Usage Examples:**
300
301
```typescript
302
function DetailScreen({ route }: { route: RouteProp<RootStackParamList, 'Detail'> }) {
303
const { itemId, category } = route.params;
304
305
return (
306
<View>
307
<Text>Screen: {route.name}</Text>
308
<Text>Item ID: {itemId}</Text>
309
<Text>Category: {category}</Text>
310
<Text>Route Key: {route.key}</Text>
311
</View>
312
);
313
}
314
```
315
316
## Type Definitions
317
318
```typescript { .api }
319
type ParamListBase = Record<string, object | undefined>;
320
321
interface Theme {
322
dark: boolean;
323
colors: {
324
primary: string;
325
background: string;
326
card: string;
327
text: string;
328
border: string;
329
notification: string;
330
};
331
}
332
333
interface StackNavigationState<ParamList extends ParamListBase> {
334
key: string;
335
index: number;
336
routeNames: string[];
337
history?: unknown[];
338
routes: Route<keyof ParamList>[];
339
type: string;
340
stale: false;
341
}
342
343
interface Route<RouteName = string> {
344
key: string;
345
name: RouteName;
346
params?: object;
347
path?: string;
348
}
349
```