or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-loading.mderror-handling.mdindex.mdnavigation-links.mdpath-search-utils.mdreact-components.mdreact-hooks.mdroute-definition.mdrouter-creation.mdssr.md

react-components.mddocs/

0

# React Components

1

2

Essential React components for router setup, navigation, route rendering, error handling, and SSR support. These components provide the UI layer for TanStack React Router functionality.

3

4

## Capabilities

5

6

### Router Provider

7

8

Main provider component that wraps the application and provides router context to all child components.

9

10

```typescript { .api }

11

/**

12

* Router provider component that wraps the application

13

* @param props - Router provider props

14

* @returns JSX element providing router context

15

*/

16

function RouterProvider<TRouter extends AnyRouter, TDehydrated = unknown>(

17

props: RouterProps<TRouter, TDehydrated>

18

): JSX.Element;

19

20

interface RouterProps<TRouter extends AnyRouter, TDehydrated = unknown> {

21

/** Router instance */

22

router: TRouter;

23

/** Dehydrated state for SSR */

24

dehydratedState?: TDehydrated;

25

/** Additional context */

26

context?: Partial<TRouter["options"]["context"]>;

27

/** Default component */

28

defaultComponent?: RouteComponent;

29

/** Default error component */

30

defaultErrorComponent?: ErrorRouteComponent;

31

/** Default pending component */

32

defaultPendingComponent?: RouteComponent;

33

/** Default not found component */

34

defaultNotFoundComponent?: NotFoundRouteComponent;

35

}

36

```

37

38

**Usage Examples:**

39

40

```typescript

41

import { RouterProvider, createRouter } from "@tanstack/react-router";

42

43

function App() {

44

return (

45

<RouterProvider

46

router={router}

47

context={{

48

user: getCurrentUser(),

49

theme: "dark",

50

}}

51

/>

52

);

53

}

54

55

// With SSR

56

function App({ dehydratedState }: { dehydratedState: any }) {

57

return (

58

<RouterProvider

59

router={router}

60

dehydratedState={dehydratedState}

61

defaultPendingComponent={() => <div>Loading...</div>}

62

/>

63

);

64

}

65

```

66

67

### Router Context Provider

68

69

Lower-level provider that only provides router context without rendering matches.

70

71

```typescript { .api }

72

/**

73

* Router context provider without match rendering

74

* @param props - Context provider props

75

* @returns JSX element providing router context only

76

*/

77

function RouterContextProvider<TRouter extends AnyRouter>(

78

props: {

79

router: TRouter;

80

children: React.ReactNode;

81

}

82

): JSX.Element;

83

```

84

85

### Navigation Link

86

87

Navigation link component with active state management, preloading, and type-safe parameters.

88

89

```typescript { .api }

90

/**

91

* Navigation link component with active state and preloading

92

* @param props - Link component props

93

* @returns JSX anchor element with router functionality

94

*/

95

function Link<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string>(

96

props: LinkProps<TRouter, TFrom>

97

): JSX.Element;

98

99

interface LinkProps<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string>

100

extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {

101

/** Destination path */

102

to?: ToPathOption;

103

/** Source path for relative navigation */

104

from?: TFrom;

105

/** Path parameters */

106

params?: MakeRouteMatch["params"];

107

/** Search parameters */

108

search?: MakeRouteMatch["search"] | ((prev: any) => any);

109

/** Hash fragment */

110

hash?: string | ((prev: string) => string);

111

/** History state */

112

state?: any;

113

/** Route mask options */

114

mask?: ToMaskOptions;

115

/** Props when link is active */

116

activeProps?: React.AnchorHTMLAttributes<HTMLAnchorElement> | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);

117

/** Props when link is inactive */

118

inactiveProps?: React.AnchorHTMLAttributes<HTMLAnchorElement> | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>);

119

/** Active matching options */

120

activeOptions?: ActiveLinkOptions;

121

/** Preload strategy */

122

preload?: false | "intent" | "render" | "viewport";

123

/** Preload delay in milliseconds */

124

preloadDelay?: number;

125

/** Use replace instead of push */

126

replace?: boolean;

127

/** Reset scroll position */

128

resetScroll?: boolean;

129

/** Scroll hash target into view */

130

hashScrollIntoView?: boolean;

131

/** Wrap navigation in startTransition */

132

startTransition?: boolean;

133

/** Enable view transitions */

134

viewTransition?: boolean;

135

/** Ignore navigation blockers */

136

ignoreBlocker?: boolean;

137

/** Child content */

138

children?: React.ReactNode | ((state: { isActive: boolean; isTransitioning: boolean }) => React.ReactNode);

139

}

140

```

141

142

**Usage Examples:**

143

144

```typescript

145

import { Link } from "@tanstack/react-router";

146

147

// Basic link

148

<Link to="/about">About</Link>

149

150

// Link with parameters

151

<Link to="/posts/$postId" params={{ postId: "123" }}>

152

View Post

153

</Link>

154

155

// Link with search params and active styles

156

<Link

157

to="/search"

158

search={{ q: "react", page: 1 }}

159

activeProps={{ className: "active" }}

160

preload="intent"

161

>

162

Search

163

</Link>

164

165

// Link with render prop children

166

<Link to="/profile">

167

{({ isActive, isTransitioning }) => (

168

<span className={isActive ? "active" : ""}>

169

Profile {isTransitioning && "..."}

170

</span>

171

)}

172

</Link>

173

```

174

175

### Route Rendering Components

176

177

Components for rendering route matches and providing outlet functionality.

178

179

```typescript { .api }

180

/**

181

* Renders a specific route match with error boundaries and suspense

182

* @param props - Match component props

183

* @returns JSX element rendering the route match

184

*/

185

function Match(props: { matchId: string }): JSX.Element;

186

187

/**

188

* Renders child route matches, acts as placeholder for nested routes

189

* @returns JSX element rendering child routes

190

*/

191

function Outlet(): JSX.Element;

192

193

/**

194

* Root component that renders all active route matches

195

* @returns JSX element rendering all matches

196

*/

197

function Matches(): JSX.Element;

198

```

199

200

**Usage Examples:**

201

202

```typescript

203

import { Match, Outlet, Matches } from "@tanstack/react-router";

204

205

// In root route component

206

function RootLayout() {

207

return (

208

<div>

209

<nav>Navigation</nav>

210

<main>

211

<Outlet />

212

</main>

213

</div>

214

);

215

}

216

217

// Custom match rendering

218

function CustomRenderer() {

219

return (

220

<div>

221

<Match matchId="specific-route-id" />

222

</div>

223

);

224

}

225

226

// Complete match rendering

227

function App() {

228

return <Matches />;

229

}

230

```

231

232

### Conditional Rendering

233

234

Component for conditionally rendering based on route matches.

235

236

```typescript { .api }

237

/**

238

* Conditionally renders children based on route match

239

* @param props - MatchRoute component props

240

* @returns JSX element or null based on match

241

*/

242

function MatchRoute<TRouter extends AnyRouter = RegisteredRouter>(

243

props: MakeMatchRouteOptions<TRouter> & {

244

children?: React.ReactNode | ((params: any) => React.ReactNode);

245

}

246

): JSX.Element | null;

247

```

248

249

**Usage Examples:**

250

251

```typescript

252

import { MatchRoute } from "@tanstack/react-router";

253

254

// Show content only on specific route

255

<MatchRoute to="/dashboard" params={{ tab: "analytics" }}>

256

<AnalyticsDashboard />

257

</MatchRoute>

258

259

// With render prop

260

<MatchRoute to="/posts/$postId">

261

{(params) => <PostDetails postId={params.postId} />}

262

</MatchRoute>

263

```

264

265

### Navigation Components

266

267

Components for programmatic navigation.

268

269

```typescript { .api }

270

/**

271

* Imperatively navigates when rendered

272

* @param props - Navigate component props

273

* @returns null (triggers navigation side effect)

274

*/

275

function Navigate<TRouter extends AnyRouter = RegisteredRouter>(

276

props: NavigateOptions<TRouter>

277

): null;

278

```

279

280

**Usage Examples:**

281

282

```typescript

283

import { Navigate } from "@tanstack/react-router";

284

285

function LoginRedirect() {

286

if (!user) {

287

return <Navigate to="/login" replace />;

288

}

289

return <Dashboard />;

290

}

291

```

292

293

### Error Handling Components

294

295

Components for handling errors and not found states.

296

297

```typescript { .api }

298

/**

299

* Error boundary for catching and handling errors

300

* @param props - CatchBoundary component props

301

* @returns JSX element with error boundary functionality

302

*/

303

function CatchBoundary(props: CatchBoundaryProps): JSX.Element;

304

305

interface CatchBoundaryProps {

306

/** Function to get reset key for boundary reset */

307

getResetKey: () => string | number;

308

/** Child components */

309

children: React.ReactNode;

310

/** Error component to render */

311

errorComponent?: ErrorRouteComponent;

312

/** Error handler callback */

313

onCatch?: (error: Error, errorInfo: React.ErrorInfo) => void;

314

}

315

316

/**

317

* Default error display component

318

* @param props - Error component props

319

* @returns JSX element displaying error

320

*/

321

function ErrorComponent(props: { error: any }): JSX.Element;

322

323

/**

324

* Boundary specifically for handling not found errors

325

* @param props - CatchNotFound component props

326

* @returns JSX element with not found error handling

327

*/

328

function CatchNotFound(props: {

329

fallback?: (error: NotFoundError) => React.ReactElement;

330

onCatch?: (error: Error, errorInfo: React.ErrorInfo) => void;

331

children: React.ReactNode;

332

}): JSX.Element;

333

334

/**

335

* Default global not found component

336

* @returns JSX element for 404 errors

337

*/

338

function DefaultGlobalNotFound(): JSX.Element;

339

```

340

341

**Usage Examples:**

342

343

```typescript

344

import { CatchBoundary, ErrorComponent, CatchNotFound } from "@tanstack/react-router";

345

346

// Error boundary with custom error component

347

<CatchBoundary

348

getResetKey={() => window.location.pathname}

349

errorComponent={({ error, reset }) => (

350

<div>

351

<h2>Something went wrong</h2>

352

<p>{error.message}</p>

353

<button onClick={reset}>Try again</button>

354

</div>

355

)}

356

onCatch={(error, errorInfo) => {

357

console.error("Route error:", error, errorInfo);

358

}}

359

>

360

<App />

361

</CatchBoundary>

362

363

// Not found boundary

364

<CatchNotFound

365

fallback={(error) => <div>Page not found: {error.message}</div>}

366

>

367

<Routes />

368

</CatchNotFound>

369

```

370

371

### Async Components

372

373

Components for handling asynchronous operations and promises.

374

375

```typescript { .api }

376

/**

377

* Suspense-based promise resolution component

378

* @param props - Await component props

379

* @returns JSX element with promise handling

380

*/

381

function Await<T>(props: AwaitOptions<T> & {

382

fallback?: React.ReactNode;

383

children: (result: T) => React.ReactNode;

384

}): JSX.Element;

385

386

interface AwaitOptions<T> {

387

/** Promise to await */

388

promise: Promise<T>;

389

}

390

```

391

392

**Usage Examples:**

393

394

```typescript

395

import { Await, defer } from "@tanstack/react-router";

396

397

// In route loader

398

const Route = createRoute({

399

path: "/posts",

400

loader: () => ({

401

posts: defer(fetchPosts()),

402

}),

403

component: PostsPage,

404

});

405

406

function PostsPage() {

407

const { posts } = Route.useLoaderData();

408

409

return (

410

<Await promise={posts} fallback={<div>Loading posts...</div>}>

411

{(posts) => (

412

<div>

413

{posts.map(post => <PostCard key={post.id} post={post} />)}

414

</div>

415

)}

416

</Await>

417

);

418

}

419

```

420

421

### Navigation Blocking

422

423

Components for blocking navigation based on conditions.

424

425

```typescript { .api }

426

/**

427

* Blocks navigation based on conditions

428

* @param props - Block component props

429

* @returns JSX element or null

430

*/

431

function Block<TRouter extends AnyRouter = RegisteredRouter>(

432

props: BlockProps<TRouter>

433

): JSX.Element | null;

434

435

interface BlockProps<TRouter extends AnyRouter = RegisteredRouter> {

436

/** Function to determine if navigation should be blocked */

437

shouldBlockFn: ShouldBlockFn;

438

/** Enable beforeunload blocking */

439

enableBeforeUnload?: boolean | (() => boolean);

440

/** Disable the blocker */

441

disabled?: boolean;

442

/** Use resolver pattern */

443

withResolver?: boolean;

444

/** Child content */

445

children?: React.ReactNode | ((resolver: any) => React.ReactNode);

446

}

447

```

448

449

### Client-Side Only Components

450

451

Components that only render on the client side.

452

453

```typescript { .api }

454

/**

455

* Only renders children on client side

456

* @param props - ClientOnly component props

457

* @returns JSX element or fallback

458

*/

459

function ClientOnly(props: {

460

children: React.ReactNode;

461

fallback?: React.ReactNode;

462

}): JSX.Element;

463

```

464

465

### Utility Components

466

467

Utility components for safe rendering and common patterns.

468

469

```typescript { .api }

470

/**

471

* Safe fragment component for wrapping children

472

* @param props - Component props with children

473

* @returns JSX fragment with children

474

*/

475

function SafeFragment(props: { children?: React.ReactNode }): JSX.Element;

476

```

477

478

**Usage Examples:**

479

480

```typescript

481

import { SafeFragment } from "@tanstack/react-router";

482

483

function MyComponent() {

484

return (

485

<SafeFragment>

486

<div>Child 1</div>

487

<div>Child 2</div>

488

</SafeFragment>

489

);

490

}

491

492

// Useful for conditional rendering

493

function ConditionalContent({ items }: { items: string[] }) {

494

if (items.length === 0) return null;

495

496

return (

497

<SafeFragment>

498

{items.map((item, index) => (

499

<div key={index}>{item}</div>

500

))}

501

</SafeFragment>

502

);

503

}

504

```

505

506

### SSR Components

507

508

Components for server-side rendering and asset management.

509

510

```typescript { .api }

511

/**

512

* Renders route-specific and manifest scripts (SSR)

513

* @returns JSX element with script tags

514

*/

515

function Scripts(): JSX.Element;

516

517

/**

518

* Renders various HTML assets (scripts, styles, meta, etc.)

519

* @param props - Asset component props

520

* @returns JSX element with asset tags

521

*/

522

function Asset(props: RouterManagedTag & { nonce?: string }): JSX.Element;

523

524

/**

525

* Renders head content from route matches

526

* @returns JSX element with head content

527

*/

528

function HeadContent(): JSX.Element;

529

530

/**

531

* Ensures scripts are only rendered once

532

* @param props - Script attributes

533

* @returns JSX script element

534

*/

535

function ScriptOnce(props: React.ScriptHTMLAttributes<HTMLScriptElement>): JSX.Element;

536

```

537

538

### Lazy Loading Components

539

540

Utilities for creating lazy-loaded route components with automatic code splitting.

541

542

```typescript { .api }

543

/**

544

* Create a lazy route component with dynamic import

545

* @param importer - Function that returns a dynamic import promise

546

* @param exportName - Named export to use (defaults to 'default')

547

* @returns Lazy component with preload capability

548

*/

549

function lazyRouteComponent<

550

T extends Record<string, any>,

551

TKey extends keyof T = 'default'

552

>(

553

importer: () => Promise<T>,

554

exportName?: TKey

555

): T[TKey] extends (props: infer TProps) => any

556

? AsyncRouteComponent<TProps>

557

: never;

558

559

/**

560

* Create a lazy component wrapper

561

* @param fn - Function that returns a dynamic import promise

562

* @returns Lazy component

563

*/

564

function lazyFn<T>(fn: () => Promise<T>): LazyComponent<T>;

565

566

/**

567

* Component types available for routes

568

* Array of valid component type strings

569

*/

570

declare const componentTypes: string[];

571

```

572

573

**Usage Examples:**

574

575

```typescript

576

import { lazyRouteComponent } from "@tanstack/react-router";

577

578

// Lazy load a default export

579

const LazyDashboard = lazyRouteComponent(() => import("./Dashboard"));

580

581

// Lazy load a named export

582

const LazySettings = lazyRouteComponent(

583

() => import("./SettingsComponents"),

584

"SettingsPage"

585

);

586

587

// Use in route definition

588

const dashboardRoute = createRoute({

589

path: "/dashboard",

590

component: LazyDashboard,

591

});

592

593

// Preload component

594

LazyDashboard.preload();

595

596

// With error handling

597

const LazyComponent = lazyRouteComponent(() =>

598

import("./Component").catch(error => {

599

console.error("Failed to load component:", error);

600

throw error;

601

})

602

);

603

```

604

605

### Scroll Management

606

607

Components for managing scroll position and restoration.

608

609

```typescript { .api }

610

/**

611

* Handles scroll position restoration

612

* @param props - ScrollRestoration component props

613

* @returns null (manages scroll as side effect)

614

*/

615

function ScrollRestoration(props: {

616

getKey?: (location: ParsedLocation) => string;

617

}): null;

618

```

619

620

## Types

621

622

### Component Props Types

623

624

```typescript { .api }

625

interface ActiveLinkOptions {

626

/** Exact path matching */

627

exact?: boolean;

628

/** Include hash in matching */

629

includeHash?: boolean;

630

/** Include search in matching */

631

includeSearch?: boolean;

632

}

633

634

interface RouterManagedTag {

635

tag: "script" | "style" | "link" | "meta";

636

attrs?: Record<string, string>;

637

children?: string;

638

}

639

```