Skip to content

Commit cb53f41

Browse files
authored
Fix issue when rendering Link/NavLink outside of matched routes (#11062)
* Fix issue when rendering Link/NavLink outside of matched routes * Update packages/react-router-dom/__tests__/link-href-test.tsx
1 parent 211c1ff commit cb53f41

File tree

3 files changed

+44
-3
lines changed

3 files changed

+44
-3
lines changed

.changeset/pretty-dolphins-relax.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@remix-run/router": patch
3+
---
4+
5+
Fix `relative="path"` issue when rendering `Link`/`NavLink` outside of matched routes

packages/react-router-dom/__tests__/link-href-test.tsx

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -927,4 +927,37 @@ describe("<Link> href", () => {
927927
);
928928
warnSpy.mockRestore();
929929
});
930+
931+
test("renders fine when used outside a route context", () => {
932+
let renderer: TestRenderer.ReactTestRenderer;
933+
TestRenderer.act(() => {
934+
renderer = TestRenderer.create(
935+
<MemoryRouter>
936+
<Link to="route">Route</Link>
937+
<Link to="path" relative="path">
938+
Path
939+
</Link>
940+
</MemoryRouter>
941+
);
942+
});
943+
944+
let anchors = renderer.root.findAllByType("a");
945+
expect(anchors.map((a) => ({ href: a.props.href, text: a.children })))
946+
.toMatchInlineSnapshot(`
947+
[
948+
{
949+
"href": "/route",
950+
"text": [
951+
"Route",
952+
],
953+
},
954+
{
955+
"href": "/path",
956+
"text": [
957+
"Path",
958+
],
959+
},
960+
]
961+
`);
962+
});
930963
});

packages/router/utils.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,9 +1191,12 @@ export function resolveTo(
11911191
if (toPathname == null) {
11921192
from = locationPathname;
11931193
} else if (isPathRelative) {
1194-
let fromSegments = routePathnames[routePathnames.length - 1]
1195-
.replace(/^\//, "")
1196-
.split("/");
1194+
let fromSegments =
1195+
routePathnames.length === 0
1196+
? []
1197+
: routePathnames[routePathnames.length - 1]
1198+
.replace(/^\//, "")
1199+
.split("/");
11971200

11981201
if (toPathname.startsWith("..")) {
11991202
let toSegments = toPathname.split("/");

0 commit comments

Comments
 (0)