Skip to content

Commit 2685a66

Browse files
lislonIgor Golovinautofix-ci[bot]
authored
fix(react-router): do not unnecessarily render notFoundComponent (#2480)
Co-authored-by: Igor Golovin <igolovin@natera.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
1 parent 6c7258a commit 2685a66

2 files changed

Lines changed: 38 additions & 3 deletions

File tree

packages/react-router/src/not-found.tsx

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,13 @@ export function CatchNotFound(props: {
5252
throw error
5353
}
5454
}}
55-
errorComponent={({ error }: { error: NotFoundError }) =>
56-
props.fallback?.(error)
57-
}
55+
errorComponent={({ error }: { error: Error }) => {
56+
if (isNotFound(error)) {
57+
return props.fallback?.(error)
58+
} else {
59+
throw error
60+
}
61+
}}
5862
>
5963
{props.children}
6064
</CatchBoundary>

packages/react-router/tests/link.test.tsx

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1095,6 +1095,37 @@ describe('Link', () => {
10951095
expect(errorText).toBeInTheDocument()
10961096
})
10971097

1098+
test('when navigating to the root with an error in component', async () => {
1099+
const notFoundComponent = vi.fn()
1100+
1101+
const rootRoute = createRootRoute({
1102+
errorComponent: () => <span>Expected rendering error message</span>,
1103+
notFoundComponent,
1104+
})
1105+
1106+
const indexRoute = createRoute({
1107+
getParentRoute: () => rootRoute,
1108+
path: '/',
1109+
component: () => {
1110+
throw new Error(
1111+
'Error from component should not render notFoundComponent',
1112+
)
1113+
},
1114+
})
1115+
1116+
const router = createRouter({
1117+
routeTree: rootRoute.addChildren([indexRoute]),
1118+
})
1119+
1120+
render(<RouterProvider router={router} />)
1121+
1122+
const errorText = await screen.findByText(
1123+
'Expected rendering error message',
1124+
)
1125+
expect(errorText).toBeInTheDocument()
1126+
expect(notFoundComponent).not.toBeCalled()
1127+
})
1128+
10981129
test('when navigating to /posts with params', async () => {
10991130
const rootRoute = createRootRoute()
11001131
const indexRoute = createRoute({

0 commit comments

Comments
 (0)