or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdnative-routing.mdnavigation-hooks.mdreact-router-components.mdreact-router-hooks.mdreact-router-utilities.mdsearch-parameters.md

react-router-utilities.mddocs/

0

# React Router Utilities

1

2

Complete re-export of React Router utility functions for path manipulation, route creation, data handling, and response generation in React Native applications.

3

4

## Capabilities

5

6

### Router Creation

7

8

#### createMemoryRouter

9

10

Creates a memory-based router suitable for React Native applications and testing environments.

11

12

```typescript { .api }

13

/**

14

* Creates a memory-based router for React Native

15

* @param routes - Array of route objects

16

* @param opts - Router configuration options

17

* @returns Router instance for use with RouterProvider

18

*/

19

function createMemoryRouter(

20

routes: RouteObject[],

21

opts?: {

22

basename?: string;

23

future?: Partial<RouterFutureConfig>;

24

hydrationData?: HydrationState;

25

initialEntries?: InitialEntry[];

26

initialIndex?: number;

27

dataStrategy?: DataStrategyFunction;

28

patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;

29

}

30

): Router;

31

```

32

33

### Path Utilities

34

35

#### createPath

36

37

Creates a path string from a partial path object.

38

39

```typescript { .api }

40

/**

41

* Creates a path string from path object

42

* @param partialPath - Partial path object

43

* @returns Complete path string

44

*/

45

function createPath(partialPath: Partial<Path>): string;

46

47

interface Path {

48

pathname?: string;

49

search?: string;

50

hash?: string;

51

}

52

```

53

54

#### generatePath

55

56

Generates a path string from a pattern and parameters.

57

58

```typescript { .api }

59

/**

60

* Generates path from pattern and parameters

61

* @param pattern - Path pattern with parameter placeholders

62

* @param params - Parameters to substitute in pattern

63

* @returns Generated path string

64

*/

65

function generatePath(pattern: string, params?: Params): string;

66

67

type Params = Record<string, string | number>;

68

```

69

70

#### parsePath

71

72

Parses a path string into its component parts.

73

74

```typescript { .api }

75

/**

76

* Parses path string into components

77

* @param path - Path string to parse

78

* @returns Path object with pathname, search, and hash

79

*/

80

function parsePath(path: string): Path;

81

```

82

83

#### resolvePath

84

85

Resolves a relative path against a base pathname.

86

87

```typescript { .api }

88

/**

89

* Resolves relative path against base pathname

90

* @param path - Path to resolve (can be relative)

91

* @param fromPathname - Base pathname to resolve against

92

* @returns Resolved path object

93

*/

94

function resolvePath(path: To, fromPathname?: string): Path;

95

96

type To = string | Partial<Path>;

97

```

98

99

### Route Matching

100

101

#### matchPath

102

103

Attempts to match a path pattern against a pathname.

104

105

```typescript { .api }

106

/**

107

* Matches path pattern against pathname

108

* @param pattern - Pattern to match (string or PathPattern object)

109

* @param pathname - Pathname to test against pattern

110

* @returns PathMatch if successful, null otherwise

111

*/

112

function matchPath(

113

pattern: PathPattern | string,

114

pathname: string

115

): PathMatch | null;

116

117

interface PathPattern {

118

path: string;

119

caseSensitive?: boolean;

120

end?: boolean;

121

}

122

123

interface PathMatch {

124

params: Params;

125

pathname: string;

126

pathnameBase: string;

127

pattern: PathPattern;

128

}

129

```

130

131

#### matchRoutes

132

133

Matches a set of routes against a location.

134

135

```typescript { .api }

136

/**

137

* Matches routes against location

138

* @param routes - Array of route objects to match

139

* @param locationArg - Location to match against

140

* @param basename - Optional basename for matching

141

* @returns Array of route matches or null

142

*/

143

function matchRoutes(

144

routes: RouteObject[],

145

locationArg: Partial<Location> | string,

146

basename?: string

147

): RouteMatch[] | null;

148

149

interface RouteMatch {

150

params: Params;

151

pathname: string;

152

pathnameBase: string;

153

route: RouteObject;

154

}

155

```

156

157

### Route Creation

158

159

#### createRoutesFromChildren

160

161

Creates route objects from React children (JSX `<Route>` elements).

162

163

```typescript { .api }

164

/**

165

* Creates route objects from React children

166

* @param children - JSX Route elements

167

* @param parentPath - Optional parent path for nested routes

168

* @returns Array of RouteObject instances

169

*/

170

function createRoutesFromChildren(

171

children: React.ReactNode,

172

parentPath?: number[]

173

): RouteObject[];

174

```

175

176

#### createRoutesFromElements

177

178

Alias for `createRoutesFromChildren`. Creates route objects from React elements.

179

180

```typescript { .api }

181

/**

182

* Alias for createRoutesFromChildren

183

* Creates route objects from React elements

184

* @param children - JSX Route elements

185

* @param parentPath - Optional parent path for nested routes

186

* @returns Array of RouteObject instances

187

*/

188

function createRoutesFromElements(

189

children: React.ReactNode,

190

parentPath?: number[]

191

): RouteObject[];

192

```

193

194

### Response Utilities

195

196

#### json

197

198

Creates a JSON response for route loaders and actions.

199

200

```typescript { .api }

201

/**

202

* Creates JSON response for loaders/actions

203

* @param object - Object to serialize as JSON

204

* @param init - Response initialization options

205

* @returns Response object with JSON content

206

*/

207

function json(object: any, init?: ResponseInit): Response;

208

```

209

210

#### redirect

211

212

Creates a redirect response for route loaders and actions.

213

214

```typescript { .api }

215

/**

216

* Creates redirect response

217

* @param url - URL to redirect to

218

* @param init - Response initialization options

219

* @returns Response object with redirect status

220

*/

221

function redirect(url: string, init?: ResponseInit): Response;

222

```

223

224

#### redirectDocument

225

226

Creates a document-level redirect response.

227

228

```typescript { .api }

229

/**

230

* Creates document-level redirect response

231

* @param url - URL to redirect to

232

* @param init - Response initialization options

233

* @returns Response object with document redirect

234

*/

235

function redirectDocument(url: string, init?: ResponseInit): Response;

236

```

237

238

#### replace

239

240

Creates a replace response for navigation.

241

242

```typescript { .api }

243

/**

244

* Creates replace response for navigation

245

* @param url - URL to replace current location

246

* @param init - Response initialization options

247

* @returns Response object with replace navigation

248

*/

249

function replace(url: string, init?: ResponseInit): Response;

250

```

251

252

#### defer

253

254

Creates a deferred response for streaming data in loaders.

255

256

```typescript { .api }

257

/**

258

* Creates deferred response for streaming

259

* @param data - Object with promises for deferred loading

260

* @param init - Response initialization options

261

* @returns Response object with deferred data

262

*/

263

function defer(data: Record<string, unknown>, init?: ResponseInit): Response;

264

```

265

266

### Error Handling

267

268

#### isRouteErrorResponse

269

270

Checks if an error is a route error response.

271

272

```typescript { .api }

273

/**

274

* Type guard for route error responses

275

* @param error - Error to check

276

* @returns Boolean indicating if error is RouteErrorResponse

277

*/

278

function isRouteErrorResponse(error: any): error is ErrorResponse;

279

280

interface ErrorResponse {

281

status: number;

282

statusText: string;

283

data: any;

284

}

285

```

286

287

### Rendering

288

289

#### renderMatches

290

291

Renders route matches into React elements.

292

293

```typescript { .api }

294

/**

295

* Renders route matches into React elements

296

* @param matches - Route matches to render

297

* @returns React element tree for matches

298

*/

299

function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;

300

```

301

302

## Usage Examples

303

304

### Memory Router Creation

305

306

```typescript

307

import { createMemoryRouter, RouterProvider } from "react-router-native";

308

309

// Basic router setup

310

const router = createMemoryRouter([

311

{

312

path: "/",

313

element: <Home />,

314

},

315

{

316

path: "/products/:id",

317

element: <Product />,

318

loader: async ({ params }) => {

319

return fetch(`/api/products/${params.id}`);

320

},

321

},

322

]);

323

324

function App() {

325

return <RouterProvider router={router} />;

326

}

327

328

// Router with initial entries for deep linking

329

const deepLinkRouter = createMemoryRouter(

330

[

331

{ path: "/", element: <Home /> },

332

{ path: "/products/:id", element: <Product /> },

333

],

334

{

335

initialEntries: ["/", "/products/123"],

336

initialIndex: 1, // Start at /products/123

337

}

338

);

339

```

340

341

### Path Manipulation

342

343

```typescript

344

import {

345

createPath,

346

generatePath,

347

parsePath,

348

resolvePath

349

} from "react-router-native";

350

351

// Create path from object

352

const path = createPath({

353

pathname: "/products",

354

search: "?sort=name",

355

hash: "#top"

356

});

357

// Result: "/products?sort=name#top"

358

359

// Generate path with parameters

360

const productPath = generatePath("/products/:id/reviews/:reviewId", {

361

id: "123",

362

reviewId: "456"

363

});

364

// Result: "/products/123/reviews/456"

365

366

// Parse path string

367

const parsed = parsePath("/products?sort=name#top");

368

// Result: { pathname: "/products", search: "?sort=name", hash: "#top" }

369

370

// Resolve relative path

371

const resolved = resolvePath("../settings", "/app/profile");

372

// Result: { pathname: "/app/settings", search: "", hash: "" }

373

```

374

375

### Route Matching

376

377

```typescript

378

import { matchPath, matchRoutes } from "react-router-native";

379

380

// Match single path

381

const match = matchPath(

382

{ path: "/products/:id", caseSensitive: false },

383

"/products/123"

384

);

385

if (match) {

386

console.log(match.params.id); // "123"

387

}

388

389

// Match multiple routes

390

const routes = [

391

{ path: "/", element: <Home /> },

392

{ path: "/products/:id", element: <Product /> },

393

];

394

395

const matches = matchRoutes(routes, "/products/123");

396

if (matches) {

397

console.log(matches[0].params.id); // "123"

398

}

399

```

400

401

### Data Loading Responses

402

403

```typescript

404

import { json, redirect, defer } from "react-router-native";

405

406

// JSON response

407

export async function productLoader({ params }) {

408

const product = await fetchProduct(params.id);

409

return json(product, { status: 200 });

410

}

411

412

// Redirect response

413

export async function productAction({ request }) {

414

const formData = await request.formData();

415

const product = await updateProduct(formData);

416

return redirect(`/products/${product.id}`);

417

}

418

419

// Deferred response for streaming

420

export async function dashboardLoader() {

421

return defer({

422

user: getUserData(), // Fast query

423

analytics: getAnalytics(), // Slow query - will stream later

424

});

425

}

426

```

427

428

### Route Object Creation

429

430

```typescript

431

import { createRoutesFromElements } from "react-router-native";

432

import { Route } from "react-router-native";

433

434

// Create routes from JSX

435

const routes = createRoutesFromElements(

436

<Route path="/" element={<Layout />}>

437

<Route index element={<Home />} />

438

<Route path="products" element={<Products />}>

439

<Route index element={<ProductList />} />

440

<Route path=":id" element={<ProductDetail />} />

441

</Route>

442

</Route>

443

);

444

445

// Use with createMemoryRouter

446

const router = createMemoryRouter(routes);

447

```

448

449

### Error Response Handling

450

451

```typescript

452

import { isRouteErrorResponse } from "react-router-native";

453

454

function ErrorBoundary() {

455

const error = useRouteError();

456

457

if (isRouteErrorResponse(error)) {

458

return (

459

<View>

460

<Text>Error {error.status}: {error.statusText}</Text>

461

<Text>{error.data}</Text>

462

</View>

463

);

464

}

465

466

return (

467

<View>

468

<Text>Unknown error occurred</Text>

469

</View>

470

);

471

}

472

```

473

474

## Types

475

476

```typescript { .api }

477

// Router types

478

interface Router {

479

// Router implementation details

480

}

481

482

interface RouteObject {

483

path?: string;

484

index?: boolean;

485

children?: React.ReactNode;

486

caseSensitive?: boolean;

487

id?: string;

488

loader?: LoaderFunction;

489

action?: ActionFunction;

490

element?: React.ReactNode | null;

491

Component?: React.ComponentType | null;

492

errorElement?: React.ReactNode | null;

493

ErrorBoundary?: React.ComponentType | null;

494

handle?: RouteHandle;

495

shouldRevalidate?: ShouldRevalidateFunction;

496

lazy?: LazyRouteFunction<RouteObject>;

497

}

498

499

// Path types

500

interface Path {

501

pathname?: string;

502

search?: string;

503

hash?: string;

504

}

505

506

interface Location extends Path {

507

state: any;

508

key: string;

509

}

510

511

// Pattern matching types

512

interface PathPattern {

513

path: string;

514

caseSensitive?: boolean;

515

end?: boolean;

516

}

517

518

interface PathMatch {

519

params: Params;

520

pathname: string;

521

pathnameBase: string;

522

pattern: PathPattern;

523

}

524

525

interface RouteMatch {

526

params: Params;

527

pathname: string;

528

pathnameBase: string;

529

route: RouteObject;

530

}

531

532

// Utility types

533

type Params = Record<string, string | number>;

534

type To = string | Partial<Path>;

535

type InitialEntry = string | Partial<Location>;

536

537

// Error types

538

interface ErrorResponse {

539

status: number;

540

statusText: string;

541

data: any;

542

}

543

544

// Function types

545

type LoaderFunction = (args: LoaderFunctionArgs) => Promise<Response> | Response | Promise<any> | any;

546

type ActionFunction = (args: ActionFunctionArgs) => Promise<Response> | Response | Promise<any> | any;

547

```

548

549

## Integration Notes

550

551

- **Memory-based**: All utilities work with memory-based routing suitable for React Native

552

- **Type Safety**: Full TypeScript support with comprehensive type definitions

553

- **Error Handling**: Built-in error response utilities and type guards

554

- **Data Loading**: Comprehensive support for loader/action patterns with streaming

555

- **Path Resolution**: Robust path manipulation utilities for complex routing scenarios