Skip to content
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/purple-islands-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Fix `generatePath` when passed a numeric `0` value parameter
8 changes: 8 additions & 0 deletions packages/react-router/__tests__/generatePath-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ describe("generatePath", () => {
})
).toBe("/courses/foo*");
});
it("handles a 0 parameter", () => {
// @ts-expect-error
// incorrect usage but worked in 6.3.0 so keep it to avoid the regression
expect(generatePath("/courses/:id", { id: 0 })).toBe("/courses/0");
// @ts-expect-error
// incorrect usage but worked in 6.3.0 so keep it to avoid the regression
expect(generatePath("/courses/*", { "*": 0 })).toBe("/courses/0");
});
});

describe("with extraneous params", () => {
Expand Down
19 changes: 6 additions & 13 deletions packages/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,9 @@ export function generatePath<Path extends string>(
// ensure `/` is added at the beginning if the path is absolute
const prefix = path.startsWith("/") ? "/" : "";

const stringify = (p: any) =>
p == null ? "" : typeof p === "string" ? p : String(p);

const segments = path
.split(/\/+/)
.map((segment, index, array) => {
Expand All @@ -770,26 +773,16 @@ export function generatePath<Path extends string>(
// only apply the splat if it's the last segment
if (isLastSegment && segment === "*") {
const star = "*" as PathParam<Path>;
const starParam = params[star];

// Apply the splat
return starParam;
return stringify(params[star]);
}

const keyMatch = segment.match(/^:(\w+)(\??)$/);
if (keyMatch) {
const [, key, optional] = keyMatch;
let param = params[key as PathParam<Path>];

if (optional === "?") {
return param == null ? "" : param;
}

if (param == null) {
invariant(false, `Missing ":${key}" param`);
}

return param;
invariant(optional === "?" || param != null, `Missing ":${key}" param`);
return stringify(param);
}

// Remove any optional markers from optional static segments
Expand Down