Skip to content

Commit

Permalink
Added better detection for absolute urls in link component (#9994)
Browse files Browse the repository at this point in the history
  • Loading branch information
lkwr committed Feb 1, 2023
1 parent fca5e55 commit 80832fb
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/afraid-scissors-rhyme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router-dom": patch
---

Improved absolute url detection in `Link` component (now also supports `mailto:` urls)
44 changes: 44 additions & 0 deletions packages/react-router-dom/__tests__/link-href-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,50 @@ describe("<Link> href", () => {

expect(renderer.root.findByType("a").props.href).toEqual("//remix.run");
});

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

expect(renderer.root.findByType("a").props.href).toEqual(
"mailto:[email protected]"
);
});

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

expect(renderer.root.findByType("a").props.href).toEqual(
"web+remix://somepath"
);
});
});

describe("in a dynamic route", () => {
Expand Down
3 changes: 1 addition & 2 deletions packages/react-router-dom/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -420,8 +420,7 @@ export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(
) {
// `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+]+:\/\//i.test(location) || location.startsWith("//");
let isAbsolute = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(location);

// Location to use in the click handler
let navigationLocation = location;
Expand Down

0 comments on commit 80832fb

Please sign in to comment.