Skip to content

Commit ce9e373

Browse files
fix: correctly match routes with optional path params followed by req… (#4838)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
1 parent 14ad18f commit ce9e373

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

packages/react-router/tests/optional-path-params.test.tsx

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,70 @@ describe('React Router - Optional Path Parameters', () => {
895895
expect(JSON.parse(paramsElement.textContent!)).toEqual(expectedParams)
896896
},
897897
)
898+
899+
it.each([
900+
{
901+
path: '/chambres',
902+
expected: {
903+
rooms: 'chambres',
904+
locale: 'undefined',
905+
},
906+
},
907+
{
908+
path: '/fr/chambres',
909+
expected: {
910+
rooms: 'chambres',
911+
locale: 'fr',
912+
},
913+
},
914+
{
915+
path: '/rooms',
916+
expected: {
917+
rooms: 'rooms',
918+
locale: 'undefined',
919+
},
920+
},
921+
{
922+
path: '/en/rooms',
923+
expected: {
924+
rooms: 'rooms',
925+
locale: 'en',
926+
},
927+
},
928+
])(
929+
'should handle routes with required param after optional param: $path',
930+
async ({ path, expected }) => {
931+
const rootRoute = createRootRoute()
932+
const roomsRoute = createRoute({
933+
getParentRoute: () => rootRoute,
934+
path: '/{-$locale}/$rooms',
935+
component: () => {
936+
const { locale, rooms } = roomsRoute.useParams()
937+
return (
938+
<div>
939+
<h1>Rooms</h1>
940+
<div data-testid="locale-param">{locale ?? 'undefined'}</div>
941+
<div data-testid="rooms-param">{rooms ?? 'undefined'}</div>
942+
<Outlet />
943+
</div>
944+
)
945+
},
946+
})
947+
948+
window.history.replaceState({}, '', path)
949+
950+
const router = createRouter({
951+
routeTree: rootRoute.addChildren([roomsRoute]),
952+
})
953+
954+
render(<RouterProvider router={router} />)
955+
await act(() => router.load())
956+
const roomsParam = await screen.findByTestId('rooms-param')
957+
expect(roomsParam).toHaveTextContent(expected.rooms)
958+
const localeParam = await screen.findByTestId('locale-param')
959+
expect(localeParam).toHaveTextContent(expected.locale)
960+
},
961+
)
898962
})
899963

900964
describe('edge cases and error handling', () => {

packages/router-core/src/path.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -811,6 +811,9 @@ function isMatch(
811811
futureRouteSegment?.type === SEGMENT_TYPE_PARAM ||
812812
futureRouteSegment?.type === SEGMENT_TYPE_WILDCARD
813813
) {
814+
if (baseSegments.length < routeSegments.length) {
815+
shouldMatchOptional = false
816+
}
814817
break
815818
}
816819
}

0 commit comments

Comments
 (0)