0
# State and Path Utilities
1
2
Utilities for converting navigation state to URL paths and vice versa, managing navigation state, finding focused routes, and handling deep linking configurations.
3
4
## Capabilities
5
6
### getPathFromState
7
8
Serialize a navigation state object to a path string for deep linking and URL generation.
9
10
```typescript { .api }
11
/**
12
* Convert navigation state to a path string
13
* @param state - Navigation state to serialize
14
* @param options - Configuration for path generation
15
* @returns Generated path string
16
*/
17
function getPathFromState(
18
state: NavigationState | PartialState<NavigationState>,
19
options?: PathConfigOptions
20
): string;
21
22
interface PathConfigOptions {
23
/** Base path to prepend to generated paths */
24
path?: string;
25
/** Initial route name for the root navigator */
26
initialRouteName?: string;
27
/** Screen path configuration mapping */
28
screens?: PathConfigMap<ParamListBase>;
29
}
30
31
type PathConfigMap<ParamList extends ParamListBase> = {
32
[RouteName in keyof ParamList]?:
33
| string
34
| {
35
path?: string;
36
exact?: boolean;
37
parse?: Record<string, (value: string) => any>;
38
stringify?: Record<string, (value: any) => string>;
39
screens?: PathConfigMap<any>;
40
initialRouteName?: string;
41
};
42
};
43
```
44
45
**Usage Examples:**
46
47
```typescript
48
import { getPathFromState } from "@react-navigation/core";
49
50
// Basic path generation
51
const state = {
52
index: 1,
53
routes: [
54
{ name: 'Home' },
55
{ name: 'Profile', params: { userId: '123' } }
56
]
57
};
58
59
const path = getPathFromState(state);
60
// Result: "/Profile/123"
61
62
// With custom path configuration
63
const config = {
64
screens: {
65
Home: '/',
66
Profile: '/user/:userId',
67
Settings: {
68
path: '/settings/:section',
69
parse: {
70
section: (value) => value.toLowerCase()
71
}
72
}
73
}
74
};
75
76
const customPath = getPathFromState(state, config);
77
// Result: "/user/123"
78
79
// Complex nested state
80
const nestedState = {
81
index: 0,
82
routes: [
83
{
84
name: 'Main',
85
state: {
86
index: 1,
87
routes: [
88
{ name: 'Home' },
89
{
90
name: 'Profile',
91
params: { userId: '123', tab: 'posts' }
92
}
93
]
94
}
95
}
96
]
97
};
98
99
const nestedPath = getPathFromState(nestedState, {
100
screens: {
101
Main: {
102
screens: {
103
Home: 'home',
104
Profile: 'profile/:userId/:tab'
105
}
106
}
107
}
108
});
109
// Result: "/profile/123/posts"
110
```
111
112
### getStateFromPath
113
114
Parse a path string to initial navigation state object for deep linking.
115
116
```typescript { .api }
117
/**
118
* Convert a path string to navigation state
119
* @param path - Path string to parse
120
* @param options - Configuration for path parsing
121
* @returns Parsed navigation state or undefined if invalid
122
*/
123
function getStateFromPath(
124
path: string,
125
options?: PathConfigOptions
126
): PartialState<NavigationState> | undefined;
127
```
128
129
**Usage Examples:**
130
131
```typescript
132
import { getStateFromPath } from "@react-navigation/core";
133
134
// Basic path parsing
135
const state = getStateFromPath('/Profile/123');
136
// Result: {
137
// routes: [{ name: 'Profile', params: { '0': '123' } }]
138
// }
139
140
// With path configuration
141
const config = {
142
screens: {
143
Home: '/',
144
Profile: '/user/:userId',
145
Settings: {
146
path: '/settings/:section',
147
parse: {
148
section: (value) => value.toLowerCase()
149
}
150
}
151
}
152
};
153
154
const parsedState = getStateFromPath('/user/123', config);
155
// Result: {
156
// routes: [{ name: 'Profile', params: { userId: '123' } }]
157
// }
158
159
// Complex nested paths
160
const nestedConfig = {
161
screens: {
162
Main: {
163
screens: {
164
Home: 'home',
165
Profile: 'profile/:userId/:tab'
166
}
167
}
168
}
169
};
170
171
const nestedState = getStateFromPath('/profile/123/posts', nestedConfig);
172
// Result: {
173
// routes: [{
174
// name: 'Main',
175
// state: {
176
// routes: [{
177
// name: 'Profile',
178
// params: { userId: '123', tab: 'posts' }
179
// }]
180
// }
181
// }]
182
// }
183
184
// Query parameters
185
const stateWithQuery = getStateFromPath('/profile/123?tab=posts&sort=date');
186
// Result: {
187
// routes: [{
188
// name: 'Profile',
189
// params: { '0': '123', tab: 'posts', sort: 'date' }
190
// }]
191
// }
192
```
193
194
### getActionFromState
195
196
Get a navigation action object that would produce the given navigation state.
197
198
```typescript { .api }
199
/**
200
* Convert navigation state to navigation action
201
* @param state - Target navigation state
202
* @param options - Configuration for action generation
203
* @returns Navigation action that produces the state
204
*/
205
function getActionFromState(
206
state: PartialState<NavigationState>,
207
options?: PathConfigOptions
208
): NavigationAction | undefined;
209
```
210
211
**Usage Examples:**
212
213
```typescript
214
import { getActionFromState } from "@react-navigation/core";
215
216
const state = {
217
routes: [
218
{ name: 'Home' },
219
{ name: 'Profile', params: { userId: '123' } }
220
]
221
};
222
223
const action = getActionFromState(state);
224
// Result: NavigationAction that navigates to Profile with userId: '123'
225
226
// Use with navigation dispatch
227
function navigateToStateFromUrl(url) {
228
const state = getStateFromPath(url, pathConfig);
229
if (state) {
230
const action = getActionFromState(state, pathConfig);
231
if (action) {
232
navigation.dispatch(action);
233
}
234
}
235
}
236
```
237
238
### findFocusedRoute
239
240
Find the currently focused route in a navigation state.
241
242
```typescript { .api }
243
/**
244
* Find the focused route in navigation state
245
* @param state - Navigation state to search
246
* @returns The focused route object
247
*/
248
function findFocusedRoute(state: NavigationState): Route<string>;
249
```
250
251
**Usage Examples:**
252
253
```typescript
254
import { findFocusedRoute } from "@react-navigation/core";
255
256
const state = {
257
index: 1,
258
routes: [
259
{ name: 'Home', key: 'home-1' },
260
{
261
name: 'Profile',
262
key: 'profile-1',
263
state: {
264
index: 0,
265
routes: [
266
{ name: 'Info', key: 'info-1' }
267
]
268
}
269
}
270
]
271
};
272
273
const focusedRoute = findFocusedRoute(state);
274
// Result: { name: 'Info', key: 'info-1' }
275
276
// Use for getting current screen name
277
function getCurrentScreenName(navigationState) {
278
const focused = findFocusedRoute(navigationState);
279
return focused.name;
280
}
281
```
282
283
### getFocusedRouteNameFromRoute
284
285
Extract the focused route name from a route object that may contain nested navigation state.
286
287
```typescript { .api }
288
/**
289
* Get focused route name from a route object
290
* @param route - Route object potentially containing nested state
291
* @returns Name of the focused route
292
*/
293
function getFocusedRouteNameFromRoute(route: Partial<Route<string>>): string | undefined;
294
```
295
296
**Usage Examples:**
297
298
```typescript
299
import { getFocusedRouteNameFromRoute } from "@react-navigation/core";
300
301
// Route with nested state
302
const route = {
303
name: 'Main',
304
state: {
305
index: 1,
306
routes: [
307
{ name: 'Home' },
308
{ name: 'Profile' }
309
]
310
}
311
};
312
313
const focusedName = getFocusedRouteNameFromRoute(route);
314
// Result: 'Profile'
315
316
// Use in navigator options
317
function getHeaderTitle(route) {
318
const routeName = getFocusedRouteNameFromRoute(route) ?? route.name;
319
320
switch (routeName) {
321
case 'Home':
322
return 'Welcome';
323
case 'Profile':
324
return 'My Profile';
325
default:
326
return routeName;
327
}
328
}
329
```
330
331
### validatePathConfig
332
333
Validate path configuration object for deep linking setup.
334
335
```typescript { .api }
336
/**
337
* Validate path configuration for correctness
338
* @param config - Path configuration to validate
339
* @throws Error if configuration is invalid
340
*/
341
function validatePathConfig(config: PathConfigOptions): void;
342
```
343
344
**Usage Examples:**
345
346
```typescript
347
import { validatePathConfig } from "@react-navigation/core";
348
349
const config = {
350
screens: {
351
Home: '/',
352
Profile: '/user/:userId',
353
Settings: {
354
path: '/settings/:section',
355
parse: {
356
section: (value) => value.toLowerCase()
357
}
358
}
359
}
360
};
361
362
try {
363
validatePathConfig(config);
364
console.log('Configuration is valid');
365
} catch (error) {
366
console.error('Invalid configuration:', error.message);
367
}
368
369
// Invalid configuration example
370
const invalidConfig = {
371
screens: {
372
Home: '/',
373
Profile: '/', // Duplicate path
374
}
375
};
376
377
validatePathConfig(invalidConfig); // Throws error
378
```
379
380
### createNavigatorFactory
381
382
Higher-order function to create Navigator, Screen, and Group components for custom navigators.
383
384
```typescript { .api }
385
/**
386
* Create navigator factory for custom navigators
387
* @param Navigator - Custom navigator component
388
* @returns Factory function that creates Navigator/Screen/Group components
389
*/
390
function createNavigatorFactory<
391
State extends NavigationState,
392
ScreenOptions extends {},
393
EventMap extends EventMapBase,
394
Navigator extends React.ComponentType<any>
395
>(
396
Navigator: Navigator
397
): <ParamList extends ParamListBase>() => TypedNavigator<{
398
ParamList: ParamList;
399
NavigatorID: string | undefined;
400
State: State;
401
ScreenOptions: ScreenOptions;
402
EventMap: EventMap;
403
NavigationList: any;
404
Navigator: Navigator;
405
}>;
406
407
interface TypedNavigator<T> {
408
Navigator: React.ComponentType<any>;
409
Screen: React.ComponentType<any>;
410
Group: React.ComponentType<any>;
411
}
412
```
413
414
**Usage Examples:**
415
416
```typescript
417
import { createNavigatorFactory, useNavigationBuilder } from "@react-navigation/core";
418
import { StackRouter } from "@react-navigation/routers";
419
420
// Custom navigator component
421
function CustomNavigator({ initialRouteName, children, ...rest }) {
422
const { state, navigation, descriptors, NavigationContent } = useNavigationBuilder(
423
StackRouter,
424
{
425
children,
426
initialRouteName,
427
...rest,
428
}
429
);
430
431
return (
432
<NavigationContent>
433
<View style={{ flex: 1 }}>
434
{state.routes.map((route, index) => {
435
const descriptor = descriptors[route.key];
436
const isFocused = state.index === index;
437
438
return (
439
<View
440
key={route.key}
441
style={{
442
flex: 1,
443
display: isFocused ? 'flex' : 'none'
444
}}
445
>
446
{descriptor.render()}
447
</View>
448
);
449
})}
450
</View>
451
</NavigationContent>
452
);
453
}
454
455
// Create navigator factory
456
const createCustomNavigator = createNavigatorFactory(CustomNavigator);
457
458
// Use the factory
459
function createMyNavigator() {
460
return createCustomNavigator<{
461
Home: undefined;
462
Profile: { userId: string };
463
}>();
464
}
465
466
const MyNavigator = createMyNavigator();
467
468
// Usage in app
469
function App() {
470
return (
471
<BaseNavigationContainer>
472
<MyNavigator.Navigator initialRouteName="Home">
473
<MyNavigator.Screen name="Home" component={HomeScreen} />
474
<MyNavigator.Screen name="Profile" component={ProfileScreen} />
475
</MyNavigator.Navigator>
476
</BaseNavigationContainer>
477
);
478
}
479
```