From cb3489f8ac3e6c52c4aa9741b34b3e7661d7da82 Mon Sep 17 00:00:00 2001 From: ChenLi Date: Thu, 12 Sep 2024 23:50:05 +0800 Subject: [PATCH] Fix encoded # in path parameter causes route to be evaluated differently --- contributors.yml | 1 + .../__tests__/navigate-encode-params-test.tsx | 40 +++++++++++++++++++ packages/router/history.ts | 1 + 3 files changed, 42 insertions(+) diff --git a/contributors.yml b/contributors.yml index e880d31108..8845029cc8 100644 --- a/contributors.yml +++ b/contributors.yml @@ -282,3 +282,4 @@ - yuleicul - zeromask1337 - zheng-chuang +- dunnai diff --git a/packages/react-router-dom/__tests__/navigate-encode-params-test.tsx b/packages/react-router-dom/__tests__/navigate-encode-params-test.tsx index 47aba5c45f..aca396061c 100644 --- a/packages/react-router-dom/__tests__/navigate-encode-params-test.tsx +++ b/packages/react-router-dom/__tests__/navigate-encode-params-test.tsx @@ -93,4 +93,44 @@ describe("navigate with params", () => { expect(node.innerHTML).toMatch(/react\+router/); }); }); + + describe("when navigate params are encoded using #", () => { + it("the encoding of the # parameter in the URL has been changed", () => { + function Start() { + let navigate = useNavigate(); + + React.useEffect(() => { + navigate("/route/react%23router/subroute/router/blog"); + }); + + return null; + } + + function Blog() { + let params = useParams(); + return

Blog: {params.routeName}-{params.subrouteName}

; + } + + act(() => { + ReactDOM.createRoot(node).render( + + + } /> + + } /> + + + } /> + + + ); + }); + + let pathname = window.location.pathname; + expect(pathname).toEqual("/route/react%23router/subroute/router/blog"); + + expect(node.innerHTML).toMatch(/react#router-router/); + }); + }); }); diff --git a/packages/router/history.ts b/packages/router/history.ts index 335645db1c..daee64390a 100644 --- a/packages/router/history.ts +++ b/packages/router/history.ts @@ -694,6 +694,7 @@ function getUrlBasedHistory( // pre-encode them since they might be part of a matching splat param from // an ancestor route href = href.replace(/ $/, "%20"); + href = typeof to === "string" ? href.replace(/#/, "%23") : href invariant( base, `No window.location.(origin|href) available to create URL for href: ${href}`