Skip to content

Commit d70c8a4

Browse files
committed
fix: handle parameters with static suffixes in generatePath
1 parent 353d05f commit d70c8a4

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

contributors.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@
187187
- jmjpro
188188
- johnpangalos
189189
- jonkoops
190+
- joseph0926
190191
- jrakotoharisoa
191192
- jrestall
192193
- juanpprieto

packages/react-router/__tests__/generatePath-test.tsx

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,4 +191,25 @@ describe("generatePath", () => {
191191

192192
consoleWarn.mockRestore();
193193
});
194+
195+
describe("with params followed by static text", () => {
196+
it("interpolates params with file extensions", () => {
197+
expect(generatePath("/books/:id.json", { id: "42" })).toBe(
198+
"/books/42.json",
199+
);
200+
expect(generatePath("/api/:resource.xml", { resource: "users" })).toBe(
201+
"/api/users.xml",
202+
);
203+
expect(generatePath("/:lang.html", { lang: "en" })).toBe("/en.html");
204+
});
205+
206+
it("handles multiple extensions", () => {
207+
expect(generatePath("/files/:name.tar.gz", { name: "archive" })).toBe(
208+
"/files/archive.tar.gz",
209+
);
210+
expect(generatePath("/:file.min.js", { file: "app" })).toBe(
211+
"/app.min.js",
212+
);
213+
});
214+
});
194215
});

packages/react-router/lib/router/utils.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1301,12 +1301,12 @@ export function generatePath<Path extends string>(
13011301
return stringify(params[star]);
13021302
}
13031303

1304-
const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
1304+
const keyMatch = segment.match(/^:([\w-]+)(\??)(.*)/);
13051305
if (keyMatch) {
1306-
const [, key, optional] = keyMatch;
1306+
const [, key, optional, suffix] = keyMatch;
13071307
let param = params[key as PathParam<Path>];
13081308
invariant(optional === "?" || param != null, `Missing ":${key}" param`);
1309-
return encodeURIComponent(stringify(param));
1309+
return encodeURIComponent(stringify(param)) + suffix;
13101310
}
13111311

13121312
// Remove any optional markers from optional static segments

0 commit comments

Comments
 (0)