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 partial object (search or hash only) pathnames losing current path #10029

Merged
merged 3 commits into from
Feb 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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/violet-apes-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router-dom": patch
---

Fix partial object (search or hash only) pathnames losing current path value
110 changes: 110 additions & 0 deletions packages/react-router-dom/__tests__/link-click-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,116 @@ describe("A <Link> click", () => {
expect(h1?.textContent).toEqual("About");
});

it("navigates to the new page when using an absolute URL on the same origin", () => {
function Home() {
return (
<div>
<h1>Home</h1>
<Link to="http://localhost/about">About</Link>
</div>
);
}

act(() => {
ReactDOM.createRoot(node).render(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route path="home" element={<Home />} />
<Route path="about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>
);
});

let anchor = node.querySelector("a");
expect(anchor).not.toBeNull();

let event: MouseEvent;
act(() => {
event = click(anchor);
});

expect(event.defaultPrevented).toBe(true);
let h1 = node.querySelector("h1");
expect(h1).not.toBeNull();
expect(h1?.textContent).toEqual("About");
});

describe("when an external absolute URL is specified", () => {
it("does not prevent default", () => {
function Home() {
return (
<div>
<h1>Home</h1>
<Link to="https://remix.run">About</Link>
</div>
);
}

act(() => {
ReactDOM.createRoot(node).render(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route path="home" element={<Home />} />
<Route path="about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>
);
});

let anchor = node.querySelector("a");
expect(anchor).not.toBeNull();

let event: MouseEvent;
act(() => {
event = click(anchor);
});

expect(event.defaultPrevented).toBe(false);
});

it("calls provided listener", () => {
let handlerCalled;
let defaultPrevented;

function Home() {
return (
<div>
<h1>Home</h1>
<Link
reloadDocument
to="https://remix.run"
onClick={(e) => {
handlerCalled = true;
defaultPrevented = e.defaultPrevented;
}}
>
About
</Link>
</div>
);
}

act(() => {
ReactDOM.createRoot(node).render(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route path="home" element={<Home />} />
<Route path="about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>
);
});

act(() => {
click(node.querySelector("a"));
});

expect(handlerCalled).toBe(true);
expect(defaultPrevented).toBe(false);
});
});

describe("when reloadDocument is specified", () => {
it("does not prevent default", () => {
function Home() {
Expand Down
66 changes: 66 additions & 0 deletions packages/react-router-dom/__tests__/link-href-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,72 @@ describe("<Link> href", () => {
"web+remix://somepath"
);
});

test('<Link to="http://localhost/inbox"> is treated as an absolute link', () => {
let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/inbox/messages"]}>
<Routes>
<Route path="inbox">
<Route
path="messages"
element={<Link to="http://localhost/inbox" />}
/>
</Route>
</Routes>
</MemoryRouter>
);
});

expect(renderer.root.findByType("a").props.href).toEqual(
"http://localhost/inbox"
);
});

test("<Link to=\"{ search: 'key=value'\"> is handled with the current pathname", () => {
let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/inbox/messages"]}>
<Routes>
<Route path="inbox">
<Route
path="messages"
element={<Link to={{ search: "key=value" }} />}
/>
</Route>
</Routes>
</MemoryRouter>
);
});

expect(renderer.root.findByType("a").props.href).toEqual(
"/inbox/messages?key=value"
);
});

test("<Link to=\"{ hash: 'hash'\"> is handled with the current pathname", () => {
let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/inbox/messages"]}>
<Routes>
<Route path="inbox">
<Route
path="messages"
element={<Link to={{ hash: "hash" }} />}
/>
</Route>
</Routes>
</MemoryRouter>
);
});

expect(renderer.root.findByType("a").props.href).toEqual(
"/inbox/messages#hash"
);
});
});

describe("in a dynamic route", () => {
Expand Down
33 changes: 17 additions & 16 deletions packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -418,31 +418,32 @@ export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(
},
ref
) {
// `location` is the unaltered href we will render in the <a> tag for absolute URLs
let location = typeof to === "string" ? to : createPath(to);
let isAbsolute = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(location);

// Location to use in the click handler
let navigationLocation = location;
// Rendered into <a href> for absolute URLs
let absoluteHref;
let isExternal = false;
if (isBrowser && isAbsolute) {

if (
isBrowser &&
typeof to === "string" &&
/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(to)
) {
Comment on lines +425 to +429
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All absolute logic now only happens when to is a string and we use to unaltered as we did before in useHref and useLinkClickHandler for non-absolute URLs

absoluteHref = to;
let currentUrl = new URL(window.location.href);
let targetUrl = location.startsWith("//")
? new URL(currentUrl.protocol + location)
: new URL(location);
let targetUrl = to.startsWith("//")
? new URL(currentUrl.protocol + to)
: new URL(to);
if (targetUrl.origin === currentUrl.origin) {
// Strip the protocol/origin for same-origin absolute URLs
navigationLocation =
targetUrl.pathname + targetUrl.search + targetUrl.hash;
to = targetUrl.pathname + targetUrl.search + targetUrl.hash;
} else {
isExternal = true;
}
}

// `href` is what we render in the <a> tag for relative URLs
let href = useHref(navigationLocation, { relative });
// Rendered into <a href> for relative URLs
let href = useHref(to, { relative });

let internalOnClick = useLinkClickHandler(navigationLocation, {
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target,
Expand All @@ -462,7 +463,7 @@ export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(
// eslint-disable-next-line jsx-a11y/anchor-has-content
<a
{...rest}
href={isAbsolute ? location : href}
href={absoluteHref || href}
onClick={isExternal || reloadDocument ? onClick : handleClick}
ref={ref}
target={target}
Expand Down