Skip to content

Fix(react-router): Generalize href to match possible routes #13797

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

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
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/slow-readers-thank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

`href()` now correctly processes routes that have an extension after the parameter or are a single optional parameter.
14 changes: 14 additions & 0 deletions packages/react-router/__tests__/href-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,35 @@ describe("href", () => {
expect(href("/a/:b", { b: "hello", z: "ignored" })).toBe("/a/hello");
expect(href("/a/:b?", { b: "hello", z: "ignored" })).toBe("/a/hello");
expect(href("/a/:b?")).toBe("/a");
expect(href("/:b?")).toBe("/");
expect(href("/a/:e-z", { "e-z": "hello" })).toBe("/a/hello");
});

it("works with repeated params", () => {
expect(href("/a/:b?/:b/:b?/:b", { b: "hello" })).toBe(
"/a/hello/hello/hello/hello",
);
expect(href("/a/:c?/:b/:c?/:b", { b: "hello" })).toBe("/a/hello/hello");
});

it("works with splats", () => {
expect(href("/a/*", { "*": "b/c" })).toBe("/a/b/c");
expect(href("/a/*", {})).toBe("/a");
});

it("works with malformed splats", () => {
// this is how packages\react-router\lib\router\utils.ts: compilePath() will handle these routes.
expect(href("/a/z*", { "*": "b/c" })).toBe("/a/z/b/c");
expect(href("/a/z*", {})).toBe("/a/z");
});

it("throws when required params are missing", () => {
expect(() => href("/a/:b")).toThrow(
`Path '/a/:b' requires param 'b' but it was not provided`,
);
});

it("works with periods", () => {
expect(href("/a/:b.zip", { b: "hello" })).toBe("/a/hello.zip");
});
});
42 changes: 22 additions & 20 deletions packages/react-router/lib/href.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,28 @@ export function href<Path extends keyof Args>(
...args: Args[Path]
): string {
let params = args[0];
return path
.split("/")
.map((segment) => {
if (segment === "*") {
return params ? params["*"] : undefined;
}
let result = path
.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
.replace(
/\/:([\w-]+)(\?)?/g, // same regex as in .\router\utils.ts: compilePath().
(_: string, param: string, isOptional) => {
const value = params ? params[param] : undefined;
if (isOptional == null && value == null) {
throw new Error(
`Path '${path}' requires param '${param}' but it was not provided`,
);
}
return value == null ? "" : "/" + value;
},
);

const match = segment.match(/^:([\w-]+)(\?)?/);
if (!match) return segment;
const param = match[1];
const value = params ? params[param] : undefined;
if (path.endsWith("*")) {
// treat trailing splat the same way as compilePath, and force it to be as if it were `/*`.
// `react-router typegen` will not generate the params for a malformed splat, causing a type error, but we can still do the correct thing here.
if (params && params["*"] != null) {
result += "/" + params["*"];
}
}

const isRequired = match[2] === undefined;
if (isRequired && value === undefined) {
throw Error(
`Path '${path}' requires param '${param}' but it was not provided`,
);
}
return value;
})
.filter((segment) => segment !== undefined)
.join("/");
return result || "/";
}