Skip to content

Commit

Permalink
Fix issue when rendering Link/NavLink outside of matched routes (#11062)
Browse files Browse the repository at this point in the history
* Fix issue when rendering Link/NavLink outside of matched routes

* Update packages/react-router-dom/__tests__/link-href-test.tsx
  • Loading branch information
brophdawg11 committed Dec 4, 2023
1 parent 211c1ff commit cb53f41
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/pretty-dolphins-relax.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@remix-run/router": patch
---

Fix `relative="path"` issue when rendering `Link`/`NavLink` outside of matched routes
33 changes: 33 additions & 0 deletions packages/react-router-dom/__tests__/link-href-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -927,4 +927,37 @@ describe("<Link> href", () => {
);
warnSpy.mockRestore();
});

test("renders fine when used outside a route context", () => {
let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter>
<Link to="route">Route</Link>
<Link to="path" relative="path">
Path
</Link>
</MemoryRouter>
);
});

let anchors = renderer.root.findAllByType("a");
expect(anchors.map((a) => ({ href: a.props.href, text: a.children })))
.toMatchInlineSnapshot(`
[
{
"href": "/route",
"text": [
"Route",
],
},
{
"href": "/path",
"text": [
"Path",
],
},
]
`);
});
});
9 changes: 6 additions & 3 deletions packages/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1191,9 +1191,12 @@ export function resolveTo(
if (toPathname == null) {
from = locationPathname;
} else if (isPathRelative) {
let fromSegments = routePathnames[routePathnames.length - 1]
.replace(/^\//, "")
.split("/");
let fromSegments =
routePathnames.length === 0
? []
: routePathnames[routePathnames.length - 1]
.replace(/^\//, "")
.split("/");

if (toPathname.startsWith("..")) {
let toSegments = toPathname.split("/");
Expand Down

0 comments on commit cb53f41

Please sign in to comment.