Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue when rendering Link/NavLink outside of matched routes #11062

Merged
merged 3 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 router context", () => {
brophdawg11 marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -1202,9 +1202,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