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