Skip to content

Commit

Permalink
Fix useLocation to receive 0 instead of null when state is set to 0 (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jungwoo3490 committed May 8, 2024
1 parent b579661 commit 127e693
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 2 deletions.
6 changes: 6 additions & 0 deletions .changeset/smooth-sloths-exist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"react-router-dom": patch
"react-router-dom-v5-compat": patch
---

Allow falsy `location.state` values passed to `<StaticRouter>`
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,4 @@
- yracnet
- yuleicul
- zheng-chuang
- jungwoo3490
2 changes: 1 addition & 1 deletion packages/react-router-dom-v5-compat/lib/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export function StaticRouter({
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state || null,
state: locationProp.state != null ? locationProp.state : null,
key: locationProp.key || "default",
};

Expand Down
26 changes: 26 additions & 0 deletions packages/react-router-dom/__tests__/static-location-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,31 @@ describe("A <StaticRouter>", () => {
key: expect.any(String),
});
});

it("retains a non-null state when passed explicitly", () => {
let location!: ReturnType<typeof useLocation>;
function LocationChecker() {
location = useLocation();
return null;
}

ReactDOMServer.renderToStaticMarkup(
<StaticRouter
location={{ pathname: "/the/path", search: "?the=query", state: 0 }}
>
<Routes>
<Route path="/the/path" element={<LocationChecker />} />
</Routes>
</StaticRouter>
);

expect(location).toEqual({
pathname: "/the/path",
search: "?the=query",
hash: "",
state: 0,
key: expect.any(String),
});
});
});
});
2 changes: 1 addition & 1 deletion packages/react-router-dom/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function StaticRouter({
pathname: locationProp.pathname || "/",
search: locationProp.search || "",
hash: locationProp.hash || "",
state: locationProp.state || null,
state: locationProp.state != null ? locationProp.state : null,
key: locationProp.key || "default",
};

Expand Down

0 comments on commit 127e693

Please sign in to comment.