Skip to content

Commit 127e693

Browse files
authored
Fix useLocation to receive 0 instead of null when state is set to 0 (#11495)
1 parent b579661 commit 127e693

File tree

5 files changed

+35
-2
lines changed

5 files changed

+35
-2
lines changed

.changeset/smooth-sloths-exist.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"react-router-dom": patch
3+
"react-router-dom-v5-compat": patch
4+
---
5+
6+
Allow falsy `location.state` values passed to `<StaticRouter>`

contributors.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,3 +254,4 @@
254254
- yracnet
255255
- yuleicul
256256
- zheng-chuang
257+
- jungwoo3490

packages/react-router-dom-v5-compat/lib/components.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ export function StaticRouter({
8686
pathname: locationProp.pathname || "/",
8787
search: locationProp.search || "",
8888
hash: locationProp.hash || "",
89-
state: locationProp.state || null,
89+
state: locationProp.state != null ? locationProp.state : null,
9090
key: locationProp.key || "default",
9191
};
9292

packages/react-router-dom/__tests__/static-location-test.tsx

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,5 +56,31 @@ describe("A <StaticRouter>", () => {
5656
key: expect.any(String),
5757
});
5858
});
59+
60+
it("retains a non-null state when passed explicitly", () => {
61+
let location!: ReturnType<typeof useLocation>;
62+
function LocationChecker() {
63+
location = useLocation();
64+
return null;
65+
}
66+
67+
ReactDOMServer.renderToStaticMarkup(
68+
<StaticRouter
69+
location={{ pathname: "/the/path", search: "?the=query", state: 0 }}
70+
>
71+
<Routes>
72+
<Route path="/the/path" element={<LocationChecker />} />
73+
</Routes>
74+
</StaticRouter>
75+
);
76+
77+
expect(location).toEqual({
78+
pathname: "/the/path",
79+
search: "?the=query",
80+
hash: "",
81+
state: 0,
82+
key: expect.any(String),
83+
});
84+
});
5985
});
6086
});

packages/react-router-dom/server.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ export function StaticRouter({
6666
pathname: locationProp.pathname || "/",
6767
search: locationProp.search || "",
6868
hash: locationProp.hash || "",
69-
state: locationProp.state || null,
69+
state: locationProp.state != null ? locationProp.state : null,
7070
key: locationProp.key || "default",
7171
};
7272

0 commit comments

Comments
 (0)