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

renderRouteNotFound.tsx

51 lines1.9 KB

1import { DefaultGlobalNotFound } from './not-found'
2import { renderInNonRouteComponentContext } from './nonRouteComponentContext'
3import type { AnyRoute, AnyRouter } from '@tanstack/router-core'
4​
5/**
6 * Renders a not found component for a route when no matching route is found.
7 *
8 * @param router - The router instance containing the route configuration
9 * @param route - The route that triggered the not found state
10 * @param data - Additional data to pass to the not found component
11 * @returns The rendered not found component or a default fallback component
12 */
13export function renderRouteNotFound(
14 router: AnyRouter,
15 route: AnyRoute,
16 data: any,
17) {
18 if (process.env.NODE_ENV !== 'production') {
19 if (!route.options.notFoundComponent) {
20 if (router.options.defaultNotFoundComponent) {
21 const DefaultNotFoundComponent = router.options.defaultNotFoundComponent
22 return renderInNonRouteComponentContext(
23 () => <DefaultNotFoundComponent {...data} />,
24 'notFoundComponent',
25 )
26 }
27​
28 console.warn(
29 `Warning: A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<p>Not Found</p>)`,
30 )
31​
32 return <DefaultGlobalNotFound />
33 }
34​
35 const NotFoundComponent = route.options.notFoundComponent
36 return renderInNonRouteComponentContext(
37 () => <NotFoundComponent {...data} />,
38 'notFoundComponent',
39 )
40 }
41​
42 if (!route.options.notFoundComponent) {
43 if (router.options.defaultNotFoundComponent) {
44 return <router.options.defaultNotFoundComponent {...data} />
45 }
46​
47 return <DefaultGlobalNotFound />
48 }
49​
50 return <route.options.notFoundComponent {...data} />