Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

RouterProvider.tsx

95 lines2.5 KB

1'use client'
2​
3import * as React from 'react'
4import { hasKeys } from '@tanstack/router-core'
5import { Matches } from './Matches'
6import { routerContext } from './routerContext'
7import type {
8 AnyRouter,
9 RegisteredRouter,
10 RouterOptions,
11} from '@tanstack/router-core'
12​
13/**
14 * Low-level provider that places the router into React context and optionally
15 * updates router options from props. Most apps should use `RouterProvider`.
16 */
17export function RouterContextProvider<
18 TRouter extends AnyRouter = RegisteredRouter,
19 TDehydrated extends Record<string, any> = Record<string, any>,
20>({
21 router,
22 children,
23 ...rest
24}: RouterProps<TRouter, TDehydrated> & {
25 children: React.ReactNode
26}) {
27 if (hasKeys(rest)) {
28 // Allow the router to update options on the router instance
29 router.update({
30 ...router.options,
31 ...rest,
32 context: {
33 ...router.options.context,
34 ...rest.context,
35 },
36 })
37 }
38​
39 const provider = (
40 <routerContext.Provider value={router as AnyRouter}>
41 {children}
42 </routerContext.Provider>
43 )
44​
45 if (router.options.Wrap) {
46 return <router.options.Wrap>{provider}</router.options.Wrap>
47 }
48​
49 return provider
51​
52/**
53 * Renders the current match presentation and provides the router to the React
54 * tree via context.
55 *
56 * Accepts mutable router options via props. Configure initialization-only
57 * options with `createRouter`.
58 *
59 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction
60 */
61export function RouterProvider<
62 TRouter extends AnyRouter = RegisteredRouter,
63 TDehydrated extends Record<string, any> = Record<string, any>,
64>({ router, ...rest }: RouterProps<TRouter, TDehydrated>) {
65 return (
66 <RouterContextProvider router={router} {...rest}>
67 <Matches />
68 </RouterContextProvider>
69 )
71​
72export type RouterProps<
73 TRouter extends AnyRouter = RegisteredRouter,
74 TDehydrated extends Record<string, any> = Record<string, any>,
75> = Omit<
76 RouterOptions<
77 TRouter['routeTree'],
78 NonNullable<TRouter['options']['trailingSlash']>,
79 NonNullable<TRouter['options']['defaultStructuralSharing']>,
80 TRouter['history'],
81 TDehydrated
82 >,
83 'context' | 'pathParamsAllowedCharacters'
84> & {
85 router: TRouter
86 context?: Partial<
87 RouterOptions<
88 TRouter['routeTree'],
89 NonNullable<TRouter['options']['trailingSlash']>,
90 NonNullable<TRouter['options']['defaultStructuralSharing']>,
91 TRouter['history'],
92 TDehydrated
93 >['context']
94 >